Practice Problems
Untitled
Arcade
Codesignal
Guesses
1
Copied!
1
def add(param1, param2):
2
return param1 + param2
3
#------------------------------------------------------------------------------------------------#
4
5
6
#------------------------------------------------------------------------------------------------#
7
8
9
def centuryFromYear(year):
10
return ((year - 1) // 100) + 1
11
12
13
#------------------------------------------------------------------------------------------------#
14
15
16
def checkPalindrome(inputString):
17
return inputString == inputString[::-1]
18
19
20
#------------------------------------------------------------------------------------------------#
21
22
23
def adjacentElementsProduct(inputArray):
24
max = inputArray[0] * inputArray[1]
25
for i in range(len(inputArray) - 1):
26
if inputArray[i] * inputArray[i + 1] > max:
27
max = inputArray[i] * inputArray[i + 1]
28
return max
29
30
31
#------------------------------------------------------------------------------------------------#
32
33
34
def shapeArea(n):
35
sum = n * 2 - 1
36
for i in range(1, (n * 2) - 1, 2):
37
sum += i * 2
38
return sum
39
40
41
#------------------------------------------------------------------------------------------------#
42
43
44
def makeArrayConsecutive2(statues):
45
return max(statues) - min(statues) - len(statues) + 1
46
47
48
#------------------------------------------------------------------------------------------------#
49
50
51
def almostIncreasingSequence(sequence):
52
i = 0
53
while i < len(sequence) - 1:
54
if not sequence[i] < sequence[i + 1]:
55
if increasingSequence(
56
sequence[:i] + sequence[i + 1 :]
57
) or increasingSequence(sequence[: i + 1] + sequence[i + 2 :]):
58
return True
59
else:
60
return False
61
i += 1
62
return True
63
64
65
#------------------------------------------------------------------------------------------------#
66
67
68
def increasingSequence(sequence):
69
for i in range(len(sequence) - 1):
70
if not sequence[i] < sequence[i + 1]:
71
return False
72
return True
73
74
75
#------------------------------------------------------------------------------------------------#
76
77
78
def matrixElementsSum(matrix):
79
if len(matrix) > 1:
80
for row in range(1, len(matrix)):
81
for room in range(len(matrix[row])):
82
if matrix[row - 1][room] == 0:
83
matrix[row][room] = 0
84
sum = 0
85
for row in matrix:
86
for room in row:
87
sum += room
88
return sum
89
90
91
#------------------------------------------------------------------------------------------------#
92
93
94
def allLongestStrings(inputArray):
95
length = max([len(word) for word in inputArray])
96
result = [word for word in inputArray if len(word) == length]
97
return result
98
99
100
#------------------------------------------------------------------------------------------------#
101
102
103
def commonCharacterCount(s1, s2):
104
count = 0
105
word2 = list(s2)
106
for letter in s1:
107
if letter in word2:
108
word2.remove(letter)
109
count += 1
110
return count
111
112
113
#------------------------------------------------------------------------------------------------#
114
115
116
def isLucky(n):
117
string = str(n)
118
top = [int(x) for x in string[: len(string) // 2]]
119
bottom = [int(x) for x in string[len(string) // 2 :]]
120
return sum(top) == sum(bottom)
121
122
123
#------------------------------------------------------------------------------------------------#
124
125
126
def sortByHeight(a):
127
treePositions = [x for x in range(len(a)) if a[x] == -1]
128
people = sorted([x for x in a if x != -1])
129
for tree in treePositions:
130
people.insert(tree, -1)
131
return people
132
133
134
import re
135
136
137
#------------------------------------------------------------------------------------------------#
138
139
140
def reverseParentheses(s):
141
while "(" in s:
142
match = re.search("\([^()]*\)", s)
143
match_string = match.group(0)[1 : len(match.group(0)) - 1]
144
reversed_match_string = match_string[::-1]
145
s = s[: match.start()] + reversed_match_string + s[match.end() :]
146
return s
147
148
149
#------------------------------------------------------------------------------------------------#
150
151
152
def alternatingSums(a):
153
team1 = sum(a[0::2])
154
team2 = sum(a[1::2])
155
return [team1, team2]
156
157
158
#------------------------------------------------------------------------------------------------#
159
160
161
def addBorder(picture):
162
picture = ["*" + string + "*" for string in picture]
163
picture = [("*" * len(picture[0]))] + picture + [("*" * len(picture[0]))]
164
return picture
165
166
167
#------------------------------------------------------------------------------------------------#
168
169
170
def areSimilar(a, b):
171
diff = [i for i in range(len(a)) if a[i] != b[i]]
172
if len(diff) == 2:
173
b[diff[0]], b[diff[1]] = b[diff[1]], b[diff[0]]
174
return a == b
175
176
177
#------------------------------------------------------------------------------------------------#
178
179
180
def arrayChange(inputArray):
181
count = 0
182
for i in range(1, len(inputArray)):
183
if inputArray[i - 1] >= inputArray[i]:
184
difference = inputArray[i - 1] - inputArray[i]
185
inputArray[i] += difference + 1
186
count += difference + 1
187
return count
188
189
190
#------------------------------------------------------------------------------------------------#
191
192
193
def palindromeRearranging(inputString):
194
inputList = sorted(inputString)
195
foundMiddle = False
196
while len(inputList) > 1:
197
if inputList[0] == inputList[1]:
198
del inputList[1]
199
elif not foundMiddle:
200
foundMiddle = True
201
else:
202
return False
203
del inputList[0]
204
return len(inputList) == 0 or not foundMiddle
205
206
207
#------------------------------------------------------------------------------------------------#
208
209
210
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
211
sameHands = yourLeft == friendsLeft and yourRight == friendsRight
212
differentHands = yourLeft == friendsRight and yourRight == friendsLeft
213
return sameHands or differentHands
214
215
216
#------------------------------------------------------------------------------------------------#
217
218
219
def arrayMaximalAdjacentDifference(inputArray):
220
diffs = []
221
for i in range(len(inputArray) - 1):
222
diffs.append(abs(inputArray[i] - inputArray[i + 1]))
223
return max(diffs)
224
225
226
#------------------------------------------------------------------------------------------------#
227
228
229
def isIPv4Address(inputString):
230
strings = [string for string in inputString.split(".")]
231
for string in strings:
232
if not string.isdecimal():
233
return False
234
nums = [int(num) for num in strings]
235
return max(nums) <= 255 and min(nums) >= 0 and len(nums) == 4
236
237
238
#------------------------------------------------------------------------------------------------#
239
240
241
def avoidObstacles(inputArray):
242
for length in range(2, max(inputArray) + 2):
243
done = True
244
jump = length
245
while jump < (max(inputArray) + length):
246
if jump in inputArray:
247
done = False
248
break
249
jump += length
250
if done:
251
return length
252
253
254
#------------------------------------------------------------------------------------------------#
255
256
257
def boxBlur(image):
258
outImage = []
259
for row in range(1, len(image) - 1):
260
line = []
261
for pixel in range(1, len(image[row]) - 1):
262
total = (
263
image[row - 1][pixel - 1]
264
+ image[row - 1][pixel]
265
+ image[row - 1][pixel + 1]
266
+ image[row][pixel - 1]
267
+ image[row][pixel]
268
+ image[row][pixel + 1]
269
+ image[row + 1][pixel - 1]
270
+ image[row + 1][pixel]
271
+ image[row + 1][pixel + 1]
272
)
273
line.append(total // 9)
274
outImage.append(line)
275
return outImage
276
277
278
#------------------------------------------------------------------------------------------------#
279
280
281
def minesweeper(matrix):
282
TOP = 0
283
BOTTOM = len(matrix) - 1
284
LEFT = 0
285
RIGHT = len(matrix[0]) - 1
286
287
outMatrix = []
288
for row in range(len(matrix)):
289
outRow = []
290
for cell in range(len(matrix[row])):
291
outRow.append(0)
292
if row != TOP:
293
outRow[cell] += matrix[row - 1][cell]
294
if row != BOTTOM:
295
outRow[cell] += matrix[row + 1][cell]
296
if cell != LEFT:
297
outRow[cell] += matrix[row][cell - 1]
298
if cell != RIGHT:
299
outRow[cell] += matrix[row][cell + 1]
300
if row != TOP and cell != LEFT:
301
outRow[cell] += matrix[row - 1][cell - 1]
302
if row != TOP and cell != RIGHT:
303
outRow[cell] += matrix[row - 1][cell + 1]
304
if row != BOTTOM and cell != LEFT:
305
outRow[cell] += matrix[row + 1][cell - 1]
306
if row != BOTTOM and cell != RIGHT:
307
outRow[cell] += matrix[row + 1][cell + 1]
308
outMatrix.append(outRow)
309
return outMatrix
310
311
312
#------------------------------------------------------------------------------------------------#
313
314
315
def arrayReplace(inputArray, elemToReplace, substitutionElem):
316
return [x if x != elemToReplace else substitutionElem for x in inputArray]
317
318
319
#------------------------------------------------------------------------------------------------#
320
321
322
def evenDigitsOnly(n):
323
return all(
324
(True if digit in ("0", "2", "4", "6", "8") else False for digit in str(n))
325
)
326
327
328
#------------------------------------------------------------------------------------------------#
329
330
331
def variableName(name):
332
return name.replace("_", "").isalnum() and not name[0].isdigit()
333
334
335
#------------------------------------------------------------------------------------------------#
336
337
338
def alphabeticShift(inputString):
339
return "".join([chr(ord(x) + 1) if x != "z" else "a" for x in inputString])
340
341
342
#------------------------------------------------------------------------------------------------#
343
344
345
def chessBoardCellColor(cell1, cell2):
346
color1 = ((ord(cell1[0]) - ord("A")) + ord(cell1[1]) - ord("1")) % 2 == 0
347
color2 = ((ord(cell2[0]) - ord("A")) + ord(cell2[1]) - ord("1")) % 2 == 0
348
return color1 == color2
349
350
351
#------------------------------------------------------------------------------------------------#
352
353
354
def circleOfNumbers(n, firstNumber):
355
return (firstNumber + (n / 2)) % n
356
357
358
#------------------------------------------------------------------------------------------------#
359
360
361
def depositProfit(deposit, rate, threshold):
362
year = 0
363
while deposit < threshold:
364
deposit *= 1 + (rate / 100)
365
year += 1
366
return year
367
368
#------------------------------------------------------------------------------------------------#
369
#------------------------------------------------------------------------------------------------#
370
371
372
def absoluteValuesSumMinimization(a):
373
sums = {}
374
for num in a:
375
total = sum([abs(a[i] - num) for i in range(len(a))])
376
if total in sums:
377
sums[total] = min(num, sums[total])
378
else:
379
sums[total] = num
380
print(sums)
381
return sums[min(sums)]
382
383
384
import itertools
385
386
387
#------------------------------------------------------------------------------------------------#
388
389
390
def stringsRearrangement(inputArray):
391
permutations = itertools.permutations(inputArray)
392
for array in permutations:
393
if testArrangement(array):
394
return True
395
return False
396
397
398
#------------------------------------------------------------------------------------------------#
399
400
401
def testArrangement(array):
402
for i in range(len(array) - 1):
403
if sum([a != b for a, b in zip(array[i], array[i + 1])]) != 1:
404
return False
405
return True
406
407
408
#------------------------------------------------------------------------------------------------#
409
410
411
def extractEachKth(inputArray, k):
412
return [inputArray[x] for x in range(len(inputArray)) if (x + 1) % k != 0]
413
414
415
#------------------------------------------------------------------------------------------------#
416
417
418
def firstDigit(inputString):
419
for char in inputString:
420
if char.isdigit():
421
return char
422
423
424
#------------------------------------------------------------------------------------------------#
425
426
427
def differentSymbolsNaive(s):
428
return len(set(s))
429
430
431
#------------------------------------------------------------------------------------------------#
432
433
434
def arrayMaxConsecutiveSum(inputArray, k):
435
sums = [sum(inputArray[:k])]
436
for i in range(1, len(inputArray) - k + 1):
437
sums.append(sums[i - 1] - inputArray[i - 1] + inputArray[i + k - 1])
438
return max(sums)
439
440
441
#------------------------------------------------------------------------------------------------#
442
443
444
def growingPlant(upSpeed, downSpeed, desiredHeight):
445
height = 0
446
days = 1
447
height += upSpeed
448
while height < desiredHeight:
449
days += 1
450
height -= downSpeed
451
height += upSpeed
452
return days
453
454
455
#------------------------------------------------------------------------------------------------#
456
457
458
def knapsackLight(value1, weight1, value2, weight2, maxW):
459
if weight1 + weight2 <= maxW:
460
return value1 + value2
461
if weight1 <= maxW and (weight2 > maxW or value1 >= value2):
462
return value1
463
if weight2 <= maxW and (weight1 > maxW or value2 >= value1):
464
return value2
465
return 0
466
467
468
#------------------------------------------------------------------------------------------------#
469
470
471
def longestDigitsPrefix(inputString):
472
for char in range(len(inputString)):
473
if not inputString[char].isdigit():
474
return inputString[:char]
475
return inputString
476
477
478
#------------------------------------------------------------------------------------------------#
479
480
481
def digitDegree(n):
482
degree = 0
483
while len(str(n)) > 1:
484
n = sum((int(digit) for digit in str(n)))
485
degree += 1
486
return degree
487
488
489
#------------------------------------------------------------------------------------------------#
490
491
492
def bishopAndPawn(bishop, pawn):
493
return abs(ord(bishop[0]) - ord(pawn[0])) == abs(ord(bishop[1]) - ord(pawn[1]))
494
495
496
#------------------------------------------------------------------------------------------------#
497
498
499
def isBeautifulString(inputString):
500
for letter in range(ord("a"), ord("z")):
501
if inputString.count(chr(letter)) < inputString.count(chr(letter + 1)):
502
return False
503
return True
504
505
506
#------------------------------------------------------------------------------------------------#
507
508
509
def findEmailDomain(address):
510
return address[address.rfind("@") + 1 :]
511
512
513
#------------------------------------------------------------------------------------------------#
514
515
516
def buildPalindrome(st):
517
if st == st[::-1]: # Check for initial palindrome
518
return st
519
index = 0
520
subStr = st[index:]
521
while subStr != subStr[::-1]: # while substring is not a palindrome
522
index += 1
523
subStr = st[index:]
524
return st + st[index - 1 :: -1]
525
526
527
#------------------------------------------------------------------------------------------------#
528
529
530
def electionsWinners(votes, k):
531
winners = 0
532
current_winner = max(votes)
533
for candidate in votes:
534
if k > 0 and candidate + k > current_winner:
535
winners += 1
536
if k == 0 and candidate == current_winner and votes.count(candidate) == 1:
537
winners += 1
538
return winners
539
540
541
#------------------------------------------------------------------------------------------------#
542
543
544
def isMAC48Address(inputString):
545
hex_chars = (
546
"1",
547
"2",
548
"3",
549
"4",
550
"5",
551
"6",
552
"7",
553
"8",
554
"9",
555
"0",
556
"A",
557
"B",
558
"C",
559
"D",
560
"E",
561
"F",
562
"a",
563
"b",
564
"c",
565
"d",
566
"e",
567
"f",
568
)
569
groups = inputString.split("-")
570
if len(groups) != 6:
571
return False
572
if not all((len(group) == 2 for group in groups)):
573
return False
574
if not all((group[0] in hex_chars and group[1] in hex_chars for group in groups)):
575
return False
576
return True
577
578
579
#------------------------------------------------------------------------------------------------#
580
581
582
def isDigit(symbol):
583
return symbol.isdigit()
584
585
586
#------------------------------------------------------------------------------------------------#
587
588
589
def lineEncoding(s):
590
count = 1
591
output = []
592
for char in range(1, len(s)):
593
if s[char] == s[char - 1]:
594
count += 1
595
else:
596
if count > 1:
597
output.append(str(count) + s[char - 1])
598
else:
599
output.append(s[char - 1])
600
count = 1
601
if s[len(s) - 1] == s[len(s) - 2]:
602
output.append(str(count) + s[len(s) - 1])
603
else:
604
output.append(s[len(s) - 1])
605
return "".join(output)
606
607
608
#------------------------------------------------------------------------------------------------#
609
610
611
def chessKnight(cell):
612
moves = 0
613
# Starting at the top left, going counter-clockwise
614
if ord(cell[0]) >= ord("b") and ord(cell[1]) <= ord("6"):
615
moves += 1
616
if ord(cell[0]) >= ord("c") and ord(cell[1]) <= ord("7"):
617
moves += 1
618
if ord(cell[0]) >= ord("c") and ord(cell[1]) >= ord("2"):
619
moves += 1
620
if ord(cell[0]) >= ord("b") and ord(cell[1]) >= ord("3"):
621
moves += 1
622
if ord(cell[0]) <= ord("g") and ord(cell[1]) >= ord("3"):
623
moves += 1
624
if ord(cell[0]) <= ord("f") and ord(cell[1]) >= ord("2"):
625
moves += 1
626
if ord(cell[0]) <= ord("f") and ord(cell[1]) <= ord("7"):
627
moves += 1
628
if ord(cell[0]) <= ord("g") and ord(cell[1]) <= ord("6"):
629
moves += 1
630
631
return moves
632
633
634
#------------------------------------------------------------------------------------------------#
635
636
637
def deleteDigit(n):
638
num = str(n)
639
highest = 0
640
for digit in range(len(num)):
641
output = num[:digit] + num[digit + 1 :]
642
if int(output) > int(highest):
643
highest = output
644
return int(highest)
645
646
647
#------------------------------------------------------------------------------------------------#
648
649
650
def longestWord(text):
651
longest = []
652
word = []
653
for char in text:
654
if ord("A") <= ord(char) <= ord("Z") or ord("a") <= ord(char) <= ord("z"):
655
word.append(char)
656
else:
657
if len(word) > len(longest):
658
longest = word
659
word = []
660
if len(word) > len(longest):
661
longest = word
662
return "".join(longest)
663
664
665
#------------------------------------------------------------------------------------------------#
666
667
668
def validTime(time):
669
groups = time.split(":")
670
if len(groups) != 2:
671
return False
672
if not (groups[0].isdigit() and groups[1].isdigit()):
673
return False
674
if int(groups[0]) > 23 or int(groups[1]) > 59:
675
return False
676
return True
677
678
679
#------------------------------------------------------------------------------------------------#
680
681
682
def sumUpNumbers(inputString):
683
total = 0
684
current_num = []
685
for char in inputString:
686
if char.isdigit():
687
current_num.append(char)
688
else:
689
if len(current_num) > 0:
690
num = int("".join(current_num))
691
total += num
692
current_num = []
693
if len(current_num) > 0:
694
num = int("".join(current_num))
695
total += num
696
return total
697
698
699
#------------------------------------------------------------------------------------------------#
700
701
702
def differentSquares(matrix):
703
squares = set()
704
for row in range(len(matrix) - 1):
705
for cell in range(len(matrix[row]) - 1):
706
square = (
707
(matrix[row][cell], matrix[row][cell + 1]),
708
(matrix[row + 1][cell], matrix[row + 1][cell + 1]),
709
)
710
squares.add(square)
711
return len(squares)
712
713
714
#------------------------------------------------------------------------------------------------#
715
716
717
def digitsProduct(product):
718
# New idea: add product to factors
719
# while max(factors) > 10: split that num into factors
720
if product == 0:
721
return 10
722
723
factors = [product]
724
while max(factors) > 9:
725
factored = findFactors(max(factors))
726
if factored:
727
factors.remove(max(factors))
728
factors.extend(factored)
729
else:
730
return -1
731
732
while factors.count(3) >= 2:
733
factors.remove(3)
734
factors.remove(3)
735
factors.append(9)
736
737
while factors.count(2) > 2:
738
factors.remove(2)
739
factors.remove(2)
740
factors.remove(2)
741
factors.append(8)
742
743
while factors.count(2) > 1:
744
factors.remove(2)
745
factors.remove(2)
746
factors.append(4)
747
748
while 2 in factors and 3 in factors:
749
factors.remove(2)
750
factors.remove(3)
751
factors.append(6)
752
753
return int("".join(map(str, sorted(factors))))
754
755
756
#------------------------------------------------------------------------------------------------#
757
758
759
def findFactors(n):
760
for i in range(2, int(n ** 0.5) + 1):
761
if n % i == 0:
762
return i, n // i
763
return False
764
765
766
#------------------------------------------------------------------------------------------------#
767
768
769
def fileNaming(names):
770
outnames = []
771
for name in names:
772
if name in outnames:
773
k = 1
774
while "{}({})".format(name, k) in outnames:
775
k += 1
776
name = "{}({})".format(name, k)
777
outnames.append(name)
778
return outnames
779
780
781
#------------------------------------------------------------------------------------------------#
782
783
784
def messageFromBinaryCode(code):
785
output = []
786
for i in range(0, len(code), 8):
787
letter = chr(int(code[i : i + 8], 2))
788
output.append(letter)
789
return "".join(output)
790
791
792
#------------------------------------------------------------------------------------------------#
793
794
795
def spiralNumbers(n):
796
LEFT = "left"
797
RIGHT = "right"
798
UP = "up"
799
DOWN = "down"
800
direction = RIGHT
801
spiral = [[0 for i in range(n)] for j in range(n)]
802
row = 0
803
cell = 0
804
for num in range(1, (n * n) + 1):
805
spiral[row][cell] = num
806
if direction == RIGHT:
807
if cell != n - 1 and spiral[row][cell + 1] == 0:
808
cell += 1
809
else:
810
direction = DOWN
811
row += 1
812
elif direction == DOWN:
813
if row != n - 1 and spiral[row + 1][cell] == 0:
814
row += 1
815
else:
816
direction = LEFT
817
cell -= 1
818
elif direction == LEFT:
819
if cell != 0 and spiral[row][cell - 1] == 0:
820
cell -= 1
821
else:
822
direction = UP
823
row -= 1
824
elif direction == UP:
825
if row != 0 and spiral[row - 1][cell] == 0:
826
row -= 1
827
else:
828
direction = RIGHT
829
cell += 1
830
return spiral
831
832
833
print(spiralNumbers(5))
834
835
836
#------------------------------------------------------------------------------------------------#
837
838
839
def sudoku(grid):
840
match = [i for i in range(1, 10)]
841
for row in grid:
842
if sorted(row) != match:
843
return False
844
for column_index in range(9):
845
column = [grid[row_index][column_index] for row_index in range(9)]
846
if sorted(column) != match:
847
return False
848
for row in range(0, 9, 3):
849
for column in range(0, 9, 3):
850
box = []
851
box.extend(grid[row][column : column + 3])
852
box.extend(grid[row + 1][column : column + 3])
853
box.extend(grid[row + 2][column : column + 3])
854
if sorted(box) != match:
855
return False
856
return True
857
858
859
#------------------------------------------------------------------------------------------------#
860
861
862
def addTwoDigits(n):
863
return (n // 10) + (n % 10)
864
865
866
#------------------------------------------------------------------------------------------------#
867
868
869
def largestNumber(n):
870
return int("9" * n)
871
872
873
#------------------------------------------------------------------------------------------------#
874
875
876
def candies(n, m):
877
return (m // n) * n
878
879
880
#------------------------------------------------------------------------------------------------#
881
882
883
def seatsInTheater(nCols, nRows, col, row):
884
return (nCols - col + 1) * (nRows - row)
885
886
887
#------------------------------------------------------------------------------------------------#
888
889
890
def maxMultiple(divisor, bound):
891
for num in range(bound, 1, -1):
892
if num % divisor == 0:
893
return num
894
return 0
895
896
897
#------------------------------------------------------------------------------------------------#
898
899
900
def circleOfNumbers(n, firstNumber):
901
return (firstNumber + (n // 2)) % n
902
903
904
#------------------------------------------------------------------------------------------------#
905
906
907
def lateRide(n):
908
hours = n // 60
909
minutes = n % 60
910
return (hours // 10) + (hours % 10) + (minutes // 10) + (minutes % 10)
911
912
913
#------------------------------------------------------------------------------------------------#
914
915
916
def phoneCall(min1, min2_10, min11, s):
917
if s < min1:
918
return 0
919
if s == min1:
920
return 1
921
if s <= min1 + (min2_10 * 9):
922
s -= min1
923
return (s // min2_10) + 1
924
s -= min1
925
s -= min2_10 * 9
926
return (s // min11) + 10
927
928
929
#------------------------------------------------------------------------------------------------#
930
931
932
def reachNextLevel(experience, threshold, reward):
933
return experience + reward >= threshold
934
935
936
#------------------------------------------------------------------------------------------------#
937
938
939
def knapsackLight(value1, weight1, value2, weight2, maxW):
940
if weight1 + weight2 <= maxW:
941
return value1 + value2
942
if weight1 <= maxW and weight2 <= maxW:
943
return max(value1, value2)
944
if weight1 <= maxW:
945
return value1
946
if weight2 <= maxW:
947
return value2
948
return 0
949
950
951
#------------------------------------------------------------------------------------------------#
952
953
954
def extraNumber(a, b, c):
955
if a == b:
956
return c
957
if a == c:
958
return b
959
return a
960
961
962
#------------------------------------------------------------------------------------------------#
963
964
965
def isInfiniteProcess(a, b):
966
return a > b or (a % 2 != b % 2)
967
968
969
#------------------------------------------------------------------------------------------------#
970
971
972
def arithmeticExpression(a, b, c):
973
return a + b == c or a - b == c or a * b == c or a / b == c
974
975
976
#------------------------------------------------------------------------------------------------#
977
978
979
def tennisSet(score1, score2):
980
if max(score1, score2) == 6 and min(score1, score2) < 5:
981
return True
982
if 5 <= min(score1, score2) <= 6 and max(score1, score2) == 7:
983
return True
984
return False
985
986
987
#------------------------------------------------------------------------------------------------#
988
989
990
def willYou(young, beautiful, loved):
991
return (young and beautiful) != loved
992
993
994
#------------------------------------------------------------------------------------------------#
995
996
997
def metroCard(lastNumberOfDays):
998
if lastNumberOfDays == 30 or lastNumberOfDays == 28:
999
return [31]
1000
return [28, 30, 31]
1001
1002
1003
#------------------------------------------------------------------------------------------------#
1004
1005
1006
def killKthBit(n, k):
1007
return n & ~(2 ** (k - 1))
1008
1009
1010
#------------------------------------------------------------------------------------------------#
1011
1012
1013
def arrayPacking(a):
1014
binary_array = [bin(num)[2:].rjust(8, "0") for num in a]
1015
out_string = "".join(binary_array[::-1])
1016
return int(out_string, 2)
1017
1018
1019
#------------------------------------------------------------------------------------------------#
1020
1021
1022
def rangeBitCount(a, b):
1023
array = list(range(a, b + 1))
1024
binary_array = [bin(num) for num in array]
1025
count_array = [binary.count("1") for binary in binary_array]
1026
return sum(count_array)
1027
1028
1029
#------------------------------------------------------------------------------------------------#
1030
1031
1032
def mirrorBits(a):
1033
binary = bin(a)[2:]
1034
return int(binary[::-1], 2)
1035
1036
1037
#------------------------------------------------------------------------------------------------#
1038
1039
1040
def secondRightmostZeroBit(n):
1041
return 2 ** bin(n)[::-1].find("0", bin(n)[::-1].find("0") + 1)
1042
1043
1044
#------------------------------------------------------------------------------------------------#
1045
1046
1047
def swapAdjacentBits(n):
1048
return ((n >> 1) & 1431655765) | ((n << 1) & 2863311530)
1049
1050
1051
#------------------------------------------------------------------------------------------------#
1052
1053
1054
def differentRightmostBit(n, m):
1055
return 2 ** bin((n ^ m))[::-1].find("1")
1056
1057
1058
#------------------------------------------------------------------------------------------------#
1059
1060
1061
def equalPairOfBits(n, m):
1062
return 2 ** bin(~(n ^ m))[::-1].find("1")
1063
1064
1065
#------------------------------------------------------------------------------------------------#
1066
1067
1068
def leastFactorial(n):
1069
factorial = 1
1070
index = 1
1071
while factorial < n:
1072
index += 1
1073
factorial *= index
1074
return factorial
1075
1076
1077
#------------------------------------------------------------------------------------------------#
1078
1079
1080
def countSumOfTwoRepresentations2(n, l, r):
1081
count = 0
1082
a = max(n - r, l)
1083
b = n - a
1084
while a <= r and a <= b:
1085
count += 1
1086
a += 1
1087
b -= 1
1088
return count
1089
1090
1091
#------------------------------------------------------------------------------------------------#
1092
1093
1094
def magicalWell(a, b, n):
1095
total = 0
1096
for i in range(n):
1097
total += a * b
1098
a += 1
1099
b += 1
1100
return total
1101
1102
1103
#------------------------------------------------------------------------------------------------#
1104
1105
1106
def lineUp(commands):
1107
count = 0
1108
smart_student = 0
1109
dumb_student = 0
1110
for command in commands:
1111
if command == "L":
1112
smart_student = (smart_student - 1) % 4
1113
dumb_student = (dumb_student + 1) % 4
1114
elif command == "R":
1115
smart_student = (smart_student + 1) % 4
1116
dumb_student = (dumb_student - 1) % 4
1117
elif command == "A":
1118
smart_student = (smart_student + 2) % 4
1119
dumb_student = (dumb_student + 2) % 4
1120
1121
if smart_student == dumb_student:
1122
count += 1
1123
return count
1124
1125
1126
#------------------------------------------------------------------------------------------------#
1127
1128
1129
def additionWithoutCarrying(param1, param2):
1130
# Convert numbers to strings
1131
str1 = str(param1)
1132
str2 = str(param2)
1133
# Pad both to the same length with zeroes (to the left of the numbers)
1134
length = max(len(str2), len(str1))
1135
str1 = str1.rjust(length, "0")
1136
str2 = str2.rjust(length, "0")
1137
output = []
1138
for num1, num2 in zip(str1, str2):
1139
result = str(int(num1) + int(num2))[-1]
1140
output.append(result)
1141
return int("".join(output))
1142
1143
1144
#------------------------------------------------------------------------------------------------#
1145
1146
1147
def appleBoxes(k):
1148
red = 0
1149
yellow = 0
1150
for i in range(1, k + 1, 2):
1151
yellow += i * i
1152
for i in range(2, k + 1, 2):
1153
red += i * i
1154
1155
return red - yellow
1156
1157
1158
#------------------------------------------------------------------------------------------------#
1159
1160
1161
def increaseNumberRoundness(n):
1162
string = str(n)
1163
# Check for immediate rejection
1164
if "0" not in string or len(string) < 2:
1165
return False
1166
# Since we know there's a 0, if it's not on
1167
# the left, then we know to accept
1168
if string[-1] != "0":
1169
return True
1170
# If there is only one 0, it must be at the end, so reject.
1171
if string.count("0") == 1:
1172
return False
1173
# If there are any numbers between the first 0
1174
# and the end of the string, then accept.
1175
first_zero = string.find("0")
1176
zero_sandwich = string[first_zero:]
1177
return zero_sandwich.count("0") != len(zero_sandwich)
1178
1179
1180
#------------------------------------------------------------------------------------------------#
1181
1182
1183
def rounders(value):
1184
length = len(str(value))
1185
magnitude = length - 1
1186
for i in range(length - 1):
1187
value = int((value / 10) + 0.5)
1188
return value * (10 ** magnitude)
1189
1190
1191
#------------------------------------------------------------------------------------------------#
1192
1193
1194
def candles(candlesNumber, makeNew):
1195
totalBurned = 0
1196
leftovers = 0
1197
while candlesNumber > 0:
1198
totalBurned += candlesNumber
1199
leftovers += candlesNumber
1200
candlesNumber = 0
1201
candlesNumber = leftovers // makeNew
1202
leftovers = leftovers % makeNew
1203
return totalBurned
1204
1205
1206
#------------------------------------------------------------------------------------------------#
1207
1208
1209
def countBlackCells(n, m):
1210
gcd = find_gcd(n, m)
1211
line_cells = n + m - gcd
1212
line_corner_cells = (gcd - 1) * 2
1213
return line_cells + line_corner_cells
1214
1215
1216
#------------------------------------------------------------------------------------------------#
1217
1218
1219
def find_gcd(a, b):
1220
while b != 0:
1221
a, b = b, a % b
1222
return a
1223
1224
1225
#------------------------------------------------------------------------------------------------#
1226
1227
1228
def createArray(size):
1229
return [1] * size
1230
1231
1232
#------------------------------------------------------------------------------------------------#
1233
1234
1235
def arrayReplace(inputArray, elemToReplace, substitutionElem):
1236
output = [
1237
elem if elem != elemToReplace else substitutionElem for elem in inputArray
1238
]
1239
return output
1240
1241
1242
#------------------------------------------------------------------------------------------------#
1243
1244
1245
def firstReverseTry(arr):
1246
if len(arr) < 2:
1247
return arr
1248
if len(arr) < 4:
1249
return arr[::-1]
1250
return arr[-1:] + arr[1:-1] + arr[:1]
1251
1252
1253
#------------------------------------------------------------------------------------------------#
1254
1255
1256
def concatenateArrays(a, b):
1257
return a + b
1258
1259
1260
#------------------------------------------------------------------------------------------------#
1261
1262
1263
def removeArrayPart(inputArray, l, r):
1264
return inputArray[:l] + inputArray[r + 1 :]
1265
1266
1267
#------------------------------------------------------------------------------------------------#
1268
1269
1270
def isSmooth(arr):
1271
if arr[0] != arr[-1]:
1272
return False
1273
if len(arr) % 2 == 0:
1274
middle = arr[len(arr) // 2] + arr[(len(arr) // 2) - 1]
1275
else:
1276
middle = arr[len(arr) // 2]
1277
return arr[0] == middle
1278
1279
1280
#------------------------------------------------------------------------------------------------#
1281
1282
1283
def replaceMiddle(arr):
1284
if len(arr) % 2 != 0:
1285
return arr
1286
right_middle = len(arr) // 2
1287
middle_value = arr[right_middle] + arr[right_middle - 1]
1288
return arr[: right_middle - 1] + [middle_value] + arr[right_middle + 1 :]
1289
1290
1291
#------------------------------------------------------------------------------------------------#
1292
1293
1294
def makeArrayConsecutive2(statues):
1295
count = 0
1296
for i in range(min(statues), max(statues)):
1297
if i not in statues:
1298
count += 1
1299
return count
1300
1301
1302
#------------------------------------------------------------------------------------------------#
1303
1304
1305
def isPower(n):
1306
if n == 1:
1307
return True
1308
1309
a = 2
1310
b = 2
1311
while a ** 2 <= n:
1312
while a ** b <= n:
1313
if a ** b == n:
1314
return True
1315
b += 1
1316
b = 2
1317
a += 1
1318
return False
1319
1320
1321
#------------------------------------------------------------------------------------------------#
1322
1323
1324
def isSumOfConsecutive2(n):
1325
count = 0
1326
right = 2
1327
arr = [1, 2]
1328
while right <= (n // 2) + 1:
1329
total = sum(arr)
1330
if total == n:
1331
count += 1
1332
del arr[0]
1333
elif total < n:
1334
right += 1
1335
arr.append(right)
1336
elif total > n:
1337
del arr[0]
1338
return count
1339
1340
1341
#------------------------------------------------------------------------------------------------#
1342
1343
1344
def squareDigitsSequence(a0):
1345
sequence = [a0]
1346
while sequence[-1] not in sequence[:-1]:
1347
next_value = 0
1348
for digit in str(sequence[-1]):
1349
next_value += int(digit) ** 2
1350
sequence.append(next_value)
1351
return len(sequence)
1352
1353
1354
#------------------------------------------------------------------------------------------------#
1355
1356
1357
def pagesNumberingWithInk(current, numberOfDigits):
1358
numberOfDigits -= len(str(current))
1359
next_digits = len(str(current + 1))
1360
while numberOfDigits >= next_digits:
1361
current += 1
1362
numberOfDigits -= next_digits
1363
next_digits = len(str(current))
1364
return current
1365
1366
1367
#------------------------------------------------------------------------------------------------#
1368
1369
1370
def comfortableNumbers(l, r):
1371
count = 0
1372
for a in range(l, r):
1373
for b in range(a + 1, r + 1):
1374
a_sum = sum(int(digit) for digit in str(a))
1375
b_sum = sum(int(digit) for digit in str(b))
1376
if b <= a + a_sum and a >= b - b_sum:
1377
count += 1
1378
return count
1379
1380
1381
#------------------------------------------------------------------------------------------------#
1382
1383
1384
def weakNumbers(n):
1385
all_factors = [count_factors(num) for num in range(1, n + 1)]
1386
weaknesses = []
1387
for num, num_factors in enumerate(all_factors, 1):
1388
weakness = 0
1389
for factor in all_factors[:num]:
1390
if factor > num_factors:
1391
weakness += 1
1392
weaknesses.append(weakness)
1393
weakest = max(weaknesses)
1394
return [weakest, weaknesses.count(weakest)]
1395
1396
1397
#------------------------------------------------------------------------------------------------#
1398
1399
1400
def count_factors(n):
1401
factors = 0
1402
for i in range(1, n + 1):
1403
if n % i == 0:
1404
factors += 1
1405
return factors
1406
1407
1408
print(weakNumbers(500))
1409
1410
import math
1411
1412
1413
#------------------------------------------------------------------------------------------------#
1414
1415
1416
def rectangleRotation(a, b):
1417
n = a / (2 ** 0.5)
1418
m = b / (2 ** 0.5)
1419
points = (math.floor(n) * math.floor(m)) + (math.ceil(n) * math.ceil(m))
1420
if math.floor(n) % 2 != math.floor(m) % 2:
1421
points -= 1
1422
return points
1423
1424
1425
# rectangleRotation(6, 4)
1426
print(rectangleRotation(8, 6))
Copied!
1
# ------------------------------------------------------------------------------------------------#
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def centuryFromYear(year):
5
return ((year - 1) // 100) + 1
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def checkPalindrome(inputString):
5
return inputString == inputString[::-1]
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def adjacentElementsProduct(inputArray):
5
max = inputArray[0] * inputArray[1]
6
for i in range(len(inputArray) - 1):
7
if inputArray[i] * inputArray[i + 1] > max:
8
max = inputArray[i] * inputArray[i + 1]
9
return max
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def shapeArea(n):
5
sum = n * 2 - 1
6
for i in range(1, (n * 2) - 1, 2):
7
sum += i * 2
8
return sum
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def makeArrayConsecutive2(statues):
5
return max(statues) - min(statues) - len(statues) + 1
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def almostIncreasingSequence(sequence):
5
i = 0
6
while i < len(sequence) - 1:
7
if not sequence[i] < sequence[i + 1]:
8
if increasingSequence(
9
sequence[:i] + sequence[i + 1 :]
10
) or increasingSequence(sequence[: i + 1] + sequence[i + 2 :]):
11
return True
12
else:
13
return False
14
i += 1
15
return True
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def increasingSequence(sequence):
5
for i in range(len(sequence) - 1):
6
if not sequence[i] < sequence[i + 1]:
7
return False
8
return True
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def matrixElementsSum(matrix):
5
if len(matrix) > 1:
6
for row in range(1, len(matrix)):
7
for room in range(len(matrix[row])):
8
if matrix[row - 1][room] == 0:
9
matrix[row][room] = 0
10
sum = 0
11
for row in matrix:
12
for room in row:
13
sum += room
14
return sum
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def allLongestStrings(inputArray):
5
length = max([len(word) for word in inputArray])
6
result = [word for word in inputArray if len(word) == length]
7
return result
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def commonCharacterCount(s1, s2):
5
count = 0
6
word2 = list(s2)
7
for letter in s1:
8
if letter in word2:
9
word2.remove(letter)
10
count += 1
11
return count
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def isLucky(n):
5
string = str(n)
6
top = [int(x) for x in string[: len(string) // 2]]
7
bottom = [int(x) for x in string[len(string) // 2 :]]
8
return sum(top) == sum(bottom)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def sortByHeight(a):
5
treePositions = [x for x in range(len(a)) if a[x] == -1]
6
people = sorted([x for x in a if x != -1])
7
for tree in treePositions:
8
people.insert(tree, -1)
9
return people
10
11
12
import re
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def reverseParentheses(s):
5
while "(" in s:
6
match = re.search("\([^()]*\)", s)
7
match_string = match.group(0)[1 : len(match.group(0)) - 1]
8
reversed_match_string = match_string[::-1]
9
s = s[: match.start()] + reversed_match_string + s[match.end() :]
10
return s
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def alternatingSums(a):
5
team1 = sum(a[0::2])
6
team2 = sum(a[1::2])
7
return [team1, team2]
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def addBorder(picture):
5
picture = ["*" + string + "*" for string in picture]
6
picture = [("*" * len(picture[0]))] + picture + [("*" * len(picture[0]))]
7
return picture
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def areSimilar(a, b):
5
diff = [i for i in range(len(a)) if a[i] != b[i]]
6
if len(diff) == 2:
7
b[diff[0]], b[diff[1]] = b[diff[1]], b[diff[0]]
8
return a == b
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def arrayChange(inputArray):
5
count = 0
6
for i in range(1, len(inputArray)):
7
if inputArray[i - 1] >= inputArray[i]:
8
difference = inputArray[i - 1] - inputArray[i]
9
inputArray[i] += difference + 1
10
count += difference + 1
11
return count
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def palindromeRearranging(inputString):
5
inputList = sorted(inputString)
6
foundMiddle = False
7
while len(inputList) > 1:
8
if inputList[0] == inputList[1]:
9
del inputList[1]
10
elif not foundMiddle:
11
foundMiddle = True
12
else:
13
return False
14
del inputList[0]
15
return len(inputList) == 0 or not foundMiddle
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
5
sameHands = yourLeft == friendsLeft and yourRight == friendsRight
6
differentHands = yourLeft == friendsRight and yourRight == friendsLeft
7
return sameHands or differentHands
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def arrayMaximalAdjacentDifference(inputArray):
5
diffs = []
6
for i in range(len(inputArray) - 1):
7
diffs.append(abs(inputArray[i] - inputArray[i + 1]))
8
return max(diffs)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def isIPv4Address(inputString):
5
strings = [string for string in inputString.split(".")]
6
for string in strings:
7
if not string.isdecimal():
8
return False
9
nums = [int(num) for num in strings]
10
return max(nums) <= 255 and min(nums) >= 0 and len(nums) == 4
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def avoidObstacles(inputArray):
5
for length in range(2, max(inputArray) + 2):
6
done = True
7
jump = length
8
while jump < (max(inputArray) + length):
9
if jump in inputArray:
10
done = False
11
break
12
jump += length
13
if done:
14
return length
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def boxBlur(image):
5
outImage = []
6
for row in range(1, len(image) - 1):
7
line = []
8
for pixel in range(1, len(image[row]) - 1):
9
total = (
10
image[row - 1][pixel - 1]
11
+ image[row - 1][pixel]
12
+ image[row - 1][pixel + 1]
13
+ image[row][pixel - 1]
14
+ image[row][pixel]
15
+ image[row][pixel + 1]
16
+ image[row + 1][pixel - 1]
17
+ image[row + 1][pixel]
18
+ image[row + 1][pixel + 1]
19
)
20
line.append(total // 9)
21
outImage.append(line)
22
return outImage
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def minesweeper(matrix):
5
TOP = 0
6
BOTTOM = len(matrix) - 1
7
LEFT = 0
8
RIGHT = len(matrix[0]) - 1
9
10
outMatrix = []
11
for row in range(len(matrix)):
12
outRow = []
13
for cell in range(len(matrix[row])):
14
outRow.append(0)
15
if row != TOP:
16
outRow[cell] += matrix[row - 1][cell]
17
if row != BOTTOM:
18
outRow[cell] += matrix[row + 1][cell]
19
if cell != LEFT:
20
outRow[cell] += matrix[row][cell - 1]
21
if cell != RIGHT:
22
outRow[cell] += matrix[row][cell + 1]
23
if row != TOP and cell != LEFT:
24
outRow[cell] += matrix[row - 1][cell - 1]
25
if row != TOP and cell != RIGHT:
26
outRow[cell] += matrix[row - 1][cell + 1]
27
if row != BOTTOM and cell != LEFT:
28
outRow[cell] += matrix[row + 1][cell - 1]
29
if row != BOTTOM and cell != RIGHT:
30
outRow[cell] += matrix[row + 1][cell + 1]
31
outMatrix.append(outRow)
32
return outMatrix
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def arrayReplace(inputArray, elemToReplace, substitutionElem):
5
return [x if x != elemToReplace else substitutionElem for x in inputArray]
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def evenDigitsOnly(n):
5
return all(
6
(True if digit in ("0", "2", "4", "6", "8") else False for digit in str(n))
7
)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def variableName(name):
5
return name.replace("_", "").isalnum() and not name[0].isdigit()
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def alphabeticShift(inputString):
5
return "".join([chr(ord(x) + 1) if x != "z" else "a" for x in inputString])
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def chessBoardCellColor(cell1, cell2):
5
color1 = ((ord(cell1[0]) - ord("A")) + ord(cell1[1]) - ord("1")) % 2 == 0
6
color2 = ((ord(cell2[0]) - ord("A")) + ord(cell2[1]) - ord("1")) % 2 == 0
7
return color1 == color2
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def circleOfNumbers(n, firstNumber):
5
return (firstNumber + (n / 2)) % n
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def depositProfit(deposit, rate, threshold):
5
year = 0
6
while deposit < threshold:
7
deposit *= 1 + (rate / 100)
8
year += 1
9
return year
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
# ------------------------------------------------------------------------------------------------#
3
4
5
def absoluteValuesSumMinimization(a):
6
sums = {}
7
for num in a:
8
total = sum([abs(a[i] - num) for i in range(len(a))])
9
if total in sums:
10
sums[total] = min(num, sums[total])
11
else:
12
sums[total] = num
13
print(sums)
14
return sums[min(sums)]
15
16
17
import itertools
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def stringsRearrangement(inputArray):
5
permutations = itertools.permutations(inputArray)
6
for array in permutations:
7
if testArrangement(array):
8
return True
9
return False
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def testArrangement(array):
5
for i in range(len(array) - 1):
6
if sum([a != b for a, b in zip(array[i], array[i + 1])]) != 1:
7
return False
8
return True
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def extractEachKth(inputArray, k):
5
return [inputArray[x] for x in range(len(inputArray)) if (x + 1) % k != 0]
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def firstDigit(inputString):
5
for char in inputString:
6
if char.isdigit():
7
return char
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def differentSymbolsNaive(s):
5
return len(set(s))
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def arrayMaxConsecutiveSum(inputArray, k):
5
sums = [sum(inputArray[:k])]
6
for i in range(1, len(inputArray) - k + 1):
7
sums.append(sums[i - 1] - inputArray[i - 1] + inputArray[i + k - 1])
8
return max(sums)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def growingPlant(upSpeed, downSpeed, desiredHeight):
5
height = 0
6
days = 1
7
height += upSpeed
8
while height < desiredHeight:
9
days += 1
10
height -= downSpeed
11
height += upSpeed
12
return days
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def knapsackLight(value1, weight1, value2, weight2, maxW):
5
if weight1 + weight2 <= maxW:
6
return value1 + value2
7
if weight1 <= maxW and (weight2 > maxW or value1 >= value2):
8
return value1
9
if weight2 <= maxW and (weight1 > maxW or value2 >= value1):
10
return value2
11
return 0
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def longestDigitsPrefix(inputString):
5
for char in range(len(inputString)):
6
if not inputString[char].isdigit():
7
return inputString[:char]
8
return inputString
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def digitDegree(n):
5
degree = 0
6
while len(str(n)) > 1:
7
n = sum((int(digit) for digit in str(n)))
8
degree += 1
9
return degree
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def bishopAndPawn(bishop, pawn):
5
return abs(ord(bishop[0]) - ord(pawn[0])) == abs(ord(bishop[1]) - ord(pawn[1]))
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def isBeautifulString(inputString):
5
for letter in range(ord("a"), ord("z")):
6
if inputString.count(chr(letter)) < inputString.count(chr(letter + 1)):
7
return False
8
return True
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def findEmailDomain(address):
5
return address[address.rfind("@") + 1 :]
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def buildPalindrome(st):
5
if st == st[::-1]: # Check for initial palindrome
6
return st
7
index = 0
8
subStr = st[index:]
9
while subStr != subStr[::-1]: # while substring is not a palindrome
10
index += 1
11
subStr = st[index:]
12
return st + st[index - 1 :: -1]
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def electionsWinners(votes, k):
5
winners = 0
6
current_winner = max(votes)
7
for candidate in votes:
8
if k > 0 and candidate + k > current_winner:
9
winners += 1
10
if k == 0 and candidate == current_winner and votes.count(candidate) == 1:
11
winners += 1
12
return winners
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def isMAC48Address(inputString):
5
hex_chars = (
6
"1",
7
"2",
8
"3",
9
"4",
10
"5",
11
"6",
12
"7",
13
"8",
14
"9",
15
"0",
16
"A",
17
"B",
18
"C",
19
"D",
20
"E",
21
"F",
22
"a",
23
"b",
24
"c",
25
"d",
26
"e",
27
"f",
28
)
29
groups = inputString.split("-")
30
if len(groups) != 6:
31
return False
32
if not all((len(group) == 2 for group in groups)):
33
return False
34
if not all((group[0] in hex_chars and group[1] in hex_chars for group in groups)):
35
return False
36
return True
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def isDigit(symbol):
5
return symbol.isdigit()
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def lineEncoding(s):
5
count = 1
6
output = []
7
for char in range(1, len(s)):
8
if s[char] == s[char - 1]:
9
count += 1
10
else:
11
if count > 1:
12
output.append(str(count) + s[char - 1])
13
else:
14
output.append(s[char - 1])
15
count = 1
16
if s[len(s) - 1] == s[len(s) - 2]:
17
output.append(str(count) + s[len(s) - 1])
18
else:
19
output.append(s[len(s) - 1])
20
return "".join(output)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def chessKnight(cell):
5
moves = 0
6
# Starting at the top left, going counter-clockwise
7
if ord(cell[0]) >= ord("b") and ord(cell[1]) <= ord("6"):
8
moves += 1
9
if ord(cell[0]) >= ord("c") and ord(cell[1]) <= ord("7"):
10
moves += 1
11
if ord(cell[0]) >= ord("c") and ord(cell[1]) >= ord("2"):
12
moves += 1
13
if ord(cell[0]) >= ord("b") and ord(cell[1]) >= ord("3"):
14
moves += 1
15
if ord(cell[0]) <= ord("g") and ord(cell[1]) >= ord("3"):
16
moves += 1
17
if ord(cell[0]) <= ord("f") and ord(cell[1]) >= ord("2"):
18
moves += 1
19
if ord(cell[0]) <= ord("f") and ord(cell[1]) <= ord("7"):
20
moves += 1
21
if ord(cell[0]) <= ord("g") and ord(cell[1]) <= ord("6"):
22
moves += 1
23
24
return moves
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def deleteDigit(n):
5
num = str(n)
6
highest = 0
7
for digit in range(len(num)):
8
output = num[:digit] + num[digit + 1 :]
9
if int(output) > int(highest):
10
highest = output
11
return int(highest)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def longestWord(text):
5
longest = []
6
word = []
7
for char in text:
8
if ord("A") <= ord(char) <= ord("Z") or ord("a") <= ord(char) <= ord("z"):
9
word.append(char)
10
else:
11
if len(word) > len(longest):
12
longest = word
13
word = []
14
if len(word) > len(longest):
15
longest = word
16
return "".join(longest)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def validTime(time):
5
groups = time.split(":")
6
if len(groups) != 2:
7
return False
8
if not (groups[0].isdigit() and groups[1].isdigit()):
9
return False
10
if int(groups[0]) > 23 or int(groups[1]) > 59:
11
return False
12
return True
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def sumUpNumbers(inputString):
5
total = 0
6
current_num = []
7
for char in inputString:
8
if char.isdigit():
9
current_num.append(char)
10
else:
11
if len(current_num) > 0:
12
num = int("".join(current_num))
13
total += num
14
current_num = []
15
if len(current_num) > 0:
16
num = int("".join(current_num))
17
total += num
18
return total
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def differentSquares(matrix):
5
squares = set()
6
for row in range(len(matrix) - 1):
7
for cell in range(len(matrix[row]) - 1):
8
square = (
9
(matrix[row][cell], matrix[row][cell + 1]),
10
(matrix[row + 1][cell], matrix[row + 1][cell + 1]),
11
)
12
squares.add(square)
13
return len(squares)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def digitsProduct(product):
5
# New idea: add product to factors
6
# while max(factors) > 10: split that num into factors
7
if product == 0:
8
return 10
9
10
factors = [product]
11
while max(factors) > 9:
12
factored = findFactors(max(factors))
13
if factored:
14
factors.remove(max(factors))
15
factors.extend(factored)
16
else:
17
return -1
18
19
while factors.count(3) >= 2:
20
factors.remove(3)
21
factors.remove(3)
22
factors.append(9)
23
24
while factors.count(2) > 2:
25
factors.remove(2)
26
factors.remove(2)
27
factors.remove(2)
28
factors.append(8)
29
30
while factors.count(2) > 1:
31
factors.remove(2)
32
factors.remove(2)
33
factors.append(4)
34
35
while 2 in factors and 3 in factors:
36
factors.remove(2)
37
factors.remove(3)
38
factors.append(6)
39
40
return int("".join(map(str, sorted(factors))))
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def findFactors(n):
5
for i in range(2, int(n ** 0.5) + 1):
6
if n % i == 0:
7
return i, n // i
8
return False
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def fileNaming(names):
5
outnames = []
6
for name in names:
7
if name in outnames:
8
k = 1
9
while "{}({})".format(name, k) in outnames:
10
k += 1
11
name = "{}({})".format(name, k)
12
outnames.append(name)
13
return outnames
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def messageFromBinaryCode(code):
5
output = []
6
for i in range(0, len(code), 8):
7
letter = chr(int(code[i : i + 8], 2))
8
output.append(letter)
9
return "".join(output)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def spiralNumbers(n):
5
LEFT = "left"
6
RIGHT = "right"
7
UP = "up"
8
DOWN = "down"
9
direction = RIGHT
10
spiral = [[0 for i in range(n)] for j in range(n)]
11
row = 0
12
cell = 0
13
for num in range(1, (n * n) + 1):
14
spiral[row][cell] = num
15
if direction == RIGHT:
16
if cell != n - 1 and spiral[row][cell + 1] == 0:
17
cell += 1
18
else:
19
direction = DOWN
20
row += 1
21
elif direction == DOWN:
22
if row != n - 1 and spiral[row + 1][cell] == 0:
23
row += 1
24
else:
25
direction = LEFT
26
cell -= 1
27
elif direction == LEFT:
28
if cell != 0 and spiral[row][cell - 1] == 0:
29
cell -= 1
30
else:
31
direction = UP
32
row -= 1
33
elif direction == UP:
34
if row != 0 and spiral[row - 1][cell] == 0:
35
row -= 1
36
else:
37
direction = RIGHT
38
cell += 1
39
return spiral
40
41
42
print(spiralNumbers(5))
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def sudoku(grid):
5
match = [i for i in range(1, 10)]
6
for row in grid:
7
if sorted(row) != match:
8
return False
9
for column_index in range(9):
10
column = [grid[row_index][column_index] for row_index in range(9)]
11
if sorted(column) != match:
12
return False
13
for row in range(0, 9, 3):
14
for column in range(0, 9, 3):
15
box = []
16
box.extend(grid[row][column : column + 3])
17
box.extend(grid[row + 1][column : column + 3])
18
box.extend(grid[row + 2][column : column + 3])
19
if sorted(box) != match:
20
return False
21
return True
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def addTwoDigits(n):
5
return (n // 10) + (n % 10)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def largestNumber(n):
5
return int("9" * n)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def candies(n, m):
5
return (m // n) * n
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def seatsInTheater(nCols, nRows, col, row):
5
return (nCols - col + 1) * (nRows - row)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def maxMultiple(divisor, bound):
5
for num in range(bound, 1, -1):
6
if num % divisor == 0:
7
return num
8
return 0
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def circleOfNumbers(n, firstNumber):
5
return (firstNumber + (n // 2)) % n
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def lateRide(n):
5
hours = n // 60
6
minutes = n % 60
7
return (hours // 10) + (hours % 10) + (minutes // 10) + (minutes % 10)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def phoneCall(min1, min2_10, min11, s):
5
if s < min1:
6
return 0
7
if s == min1:
8
return 1
9
if s <= min1 + (min2_10 * 9):
10
s -= min1
11
return (s // min2_10) + 1
12
s -= min1
13
s -= min2_10 * 9
14
return (s // min11) + 10
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def reachNextLevel(experience, threshold, reward):
5
return experience + reward >= threshold
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def knapsackLight(value1, weight1, value2, weight2, maxW):
5
if weight1 + weight2 <= maxW:
6
return value1 + value2
7
if weight1 <= maxW and weight2 <= maxW:
8
return max(value1, value2)
9
if weight1 <= maxW:
10
return value1
11
if weight2 <= maxW:
12
return value2
13
return 0
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def extraNumber(a, b, c):
5
if a == b:
6
return c
7
if a == c:
8
return b
9
return a
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def isInfiniteProcess(a, b):
5
return a > b or (a % 2 != b % 2)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def arithmeticExpression(a, b, c):
5
return a + b == c or a - b == c or a * b == c or a / b == c
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def tennisSet(score1, score2):
5
if max(score1, score2) == 6 and min(score1, score2) < 5:
6
return True
7
if 5 <= min(score1, score2) <= 6 and max(score1, score2) == 7:
8
return True
9
return False
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def willYou(young, beautiful, loved):
5
return (young and beautiful) != loved
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def metroCard(lastNumberOfDays):
5
if lastNumberOfDays == 30 or lastNumberOfDays == 28:
6
return [31]
7
return [28, 30, 31]
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def killKthBit(n, k):
5
return n & ~(2 ** (k - 1))
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def arrayPacking(a):
5
binary_array = [bin(num)[2:].rjust(8, "0") for num in a]
6
out_string = "".join(binary_array[::-1])
7
return int(out_string, 2)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def rangeBitCount(a, b):
5
array = list(range(a, b + 1))
6
binary_array = [bin(num) for num in array]
7
count_array = [binary.count("1") for binary in binary_array]
8
return sum(count_array)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def mirrorBits(a):
5
binary = bin(a)[2:]
6
return int(binary[::-1], 2)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def secondRightmostZeroBit(n):
5
return 2 ** bin(n)[::-1].find("0", bin(n)[::-1].find("0") + 1)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def swapAdjacentBits(n):
5
return ((n >> 1) & 1431655765) | ((n << 1) & 2863311530)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def differentRightmostBit(n, m):
5
return 2 ** bin((n ^ m))[::-1].find("1")
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def equalPairOfBits(n, m):
5
return 2 ** bin(~(n ^ m))[::-1].find("1")
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def leastFactorial(n):
5
factorial = 1
6
index = 1
7
while factorial < n:
8
index += 1
9
factorial *= index
10
return factorial
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def countSumOfTwoRepresentations2(n, l, r):
5
count = 0
6
a = max(n - r, l)
7
b = n - a
8
while a <= r and a <= b:
9
count += 1
10
a += 1
11
b -= 1
12
return count
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def magicalWell(a, b, n):
5
total = 0
6
for i in range(n):
7
total += a * b
8
a += 1
9
b += 1
10
return total
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def lineUp(commands):
5
count = 0
6
smart_student = 0
7
dumb_student = 0
8
for command in commands:
9
if command == "L":
10
smart_student = (smart_student - 1) % 4
11
dumb_student = (dumb_student + 1) % 4
12
elif command == "R":
13
smart_student = (smart_student + 1) % 4
14
dumb_student = (dumb_student - 1) % 4
15
elif command == "A":
16
smart_student = (smart_student + 2) % 4
17
dumb_student = (dumb_student + 2) % 4
18
19
if smart_student == dumb_student:
20
count += 1
21
return count
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def additionWithoutCarrying(param1, param2):
5
# Convert numbers to strings
6
str1 = str(param1)
7
str2 = str(param2)
8
# Pad both to the same length with zeroes (to the left of the numbers)
9
length = max(len(str2), len(str1))
10
str1 = str1.rjust(length, "0")
11
str2 = str2.rjust(length, "0")
12
output = []
13
for num1, num2 in zip(str1, str2):
14
result = str(int(num1) + int(num2))[-1]
15
output.append(result)
16
return int("".join(output))
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def appleBoxes(k):
5
red = 0
6
yellow = 0
7
for i in range(1, k + 1, 2):
8
yellow += i * i
9
for i in range(2, k + 1, 2):
10
red += i * i
11
12
return red - yellow
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def increaseNumberRoundness(n):
5
string = str(n)
6
# Check for immediate rejection
7
if "0" not in string or len(string) < 2:
8
return False
9
# Since we know there's a 0, if it's not on
10
# the left, then we know to accept
11
if string[-1] != "0":
12
return True
13
# If there is only one 0, it must be at the end, so reject.
14
if string.count("0") == 1:
15
return False
16
# If there are any numbers between the first 0
17
# and the end of the string, then accept.
18
first_zero = string.find("0")
19
zero_sandwich = string[first_zero:]
20
return zero_sandwich.count("0") != len(zero_sandwich)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def rounders(value):
5
length = len(str(value))
6
magnitude = length - 1
7
for i in range(length - 1):
8
value = int((value / 10) + 0.5)
9
return value * (10 ** magnitude)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def candles(candlesNumber, makeNew):
5
totalBurned = 0
6
leftovers = 0
7
while candlesNumber > 0:
8
totalBurned += candlesNumber
9
leftovers += candlesNumber
10
candlesNumber = 0
11
candlesNumber = leftovers // makeNew
12
leftovers = leftovers % makeNew
13
return totalBurned
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def countBlackCells(n, m):
5
gcd = find_gcd(n, m)
6
line_cells = n + m - gcd
7
line_corner_cells = (gcd - 1) * 2
8
return line_cells + line_corner_cells
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def find_gcd(a, b):
5
while b != 0:
6
a, b = b, a % b
7
return a
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def createArray(size):
5
return [1] * size
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def arrayReplace(inputArray, elemToReplace, substitutionElem):
5
output = [
6
elem if elem != elemToReplace else substitutionElem for elem in inputArray
7
]
8
return output
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def firstReverseTry(arr):
5
if len(arr) < 2:
6
return arr
7
if len(arr) < 4:
8
return arr[::-1]
9
return arr[-1:] + arr[1:-1] + arr[:1]
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def concatenateArrays(a, b):
5
return a + b
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def removeArrayPart(inputArray, l, r):
5
return inputArray[:l] + inputArray[r + 1 :]
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def isSmooth(arr):
5
if arr[0] != arr[-1]:
6
return False
7
if len(arr) % 2 == 0:
8
middle = arr[len(arr) // 2] + arr[(len(arr) // 2) - 1]
9
else:
10
middle = arr[len(arr) // 2]
11
return arr[0] == middle
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def replaceMiddle(arr):
5
if len(arr) % 2 != 0:
6
return arr
7
right_middle = len(arr) // 2
8
middle_value = arr[right_middle] + arr[right_middle - 1]
9
return arr[: right_middle - 1] + [middle_value] + arr[right_middle + 1 :]
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def makeArrayConsecutive2(statues):
5
count = 0
6
for i in range(min(statues), max(statues)):
7
if i not in statues:
8
count += 1
9
return count
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def isPower(n):
5
if n == 1:
6
return True
7
8
a = 2
9
b = 2
10
while a ** 2 <= n:
11
while a ** b <= n:
12
if a ** b == n:
13
return True
14
b += 1
15
b = 2
16
a += 1
17
return False
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def isSumOfConsecutive2(n):
5
count = 0
6
right = 2
7
arr = [1, 2]
8
while right <= (n // 2) + 1:
9
total = sum(arr)
10
if total == n:
11
count += 1
12
del arr[0]
13
elif total < n:
14
right += 1
15
arr.append(right)
16
elif total > n:
17
del arr[0]
18
return count
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def squareDigitsSequence(a0):
5
sequence = [a0]
6
while sequence[-1] not in sequence[:-1]:
7
next_value = 0
8
for digit in str(sequence[-1]):
9
next_value += int(digit) ** 2
10
sequence.append(next_value)
11
return len(sequence)
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def pagesNumberingWithInk(current, numberOfDigits):
5
numberOfDigits -= len(str(current))
6
next_digits = len(str(current + 1))
7
while numberOfDigits >= next_digits:
8
current += 1
9
numberOfDigits -= next_digits
10
next_digits = len(str(current))
11
return current
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def comfortableNumbers(l, r):
5
count = 0
6
for a in range(l, r):
7
for b in range(a + 1, r + 1):
8
a_sum = sum(int(digit) for digit in str(a))
9
b_sum = sum(int(digit) for digit in str(b))
10
if b <= a + a_sum and a >= b - b_sum:
11
count += 1
12
return count
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def weakNumbers(n):
5
all_factors = [count_factors(num) for num in range(1, n + 1)]
6
weaknesses = []
7
for num, num_factors in enumerate(all_factors, 1):
8
weakness = 0
9
for factor in all_factors[:num]:
10
if factor > num_factors:
11
weakness += 1
12
weaknesses.append(weakness)
13
weakest = max(weaknesses)
14
return [weakest, weaknesses.count(weakest)]
Copied!
1
# ------------------------------------------------------------------------------------------------#
2
3
4
def count_factors(n):
5
factors = 0
6
for i in range(1, n + 1):
7
if n % i == 0:
8
factors += 1
9
return factors
10
11
12
print(weakNumbers(500))
13
14
import math
Copied!
```py

------------------------------------------------------------------------------------------------#

1
Given an array A return an output array B of size `[A.length - 2]` where B[i] = 1 if sides A[i],A[i+1] and A[i+2] form a triangle. Otherwise, set B[i] = 0.\
2
ex. A = [1, 2, 2, 5, 5, 4] should return B = [1,0,0,1]
3
4
Given two strings a and b, merge the strings so that the letters are added in alternating order starting with string a. If one string is longer than the other, then append the letters to the end of the merged string.\
5
ex. "abcd", "efghi" -> "aebfcgdhi"\
6
ex. "", "abcd" -> "abcd"\
7
ex. "abcdefg", "zxy" -> "azbxycdefg"\
8
Pretty easy. Just interlace them like a merge sort.
9
10
Given a string s, return the longest and lexicographically smallest palindromic string that can be formed from the characters.\
11
ex. "abbaa" -> "abba"\
12
ex. "adeadeadevue" -> "adeeaeeda"
13
14
```
15
def smallestPalindrome(s):
16
if not s:
17
return s
18
res = []
19
counts = collections.Counter(s)
20
alphabet = "abcdefghijklmnopqrstuvwxyz"
21
middle_letter = ""
22
for letter in alphabet:
23
count = counts.get(letter, 0)
24
if count > 0:
25
if count % 2 == 1 and middle_letter == "":
26
middle_letter = letter
27
res.append(letter * ((count - 1) // 2))
28
else:
29
res.append(letter * (count // 2))
30
first= "".join(sb)
31
return first + middle_letter + first[::-1]
32
33
```
34
35
* * * * *
36
37
Easy-Medium:\
38
Given a list of strings `string_list` and a list of words `words`, determine whether each word in `words`\
39
can be formed as a concatenation of consecutive strings in `string_list` starting with index 0.\
40
ex. word = "oneTwoThree", string_list = ["one", "Three", "Two"] is false because the words aren't consecutive in string_list\
41
ex. word = "one", string_list = ["one", "Three", "Two"] is True because the concatenation stops at the first index in string_list\
42
ex. word = "one", string_list = ["One", "one", "Two"] is False because the concatenation doesn't start at 0.\
43
Just use the base idea from the LeetCode problem and then modify it for the consecutive concatenation requirement. It's actually easier than the LeetCode problem.
44
45
* * * * *
46
47
Medium:
48
49
Beauty of a matrix.\
50
Given an n x n matrix `M` and an int `k` where `n % k == 0`, divide the M into blocks of size `k x k` starting with the top left corner. i.e. a 9x9 matrix turns into 9 3x3s. The *beauty* of a block is the smallest positive number missing from a block. Rearrange `M` so that the blocks with the lowest beauty come before those with higher beauty (top left to bottom right). In a tie, you should place the block that came first in M before the other block.\
51
`Just do what the problem says. Make an array A = [(int beauty, int[][] block)...] and a stable sorting algorithm will handle things. Then glue the blocks back into the matrix.`
52
53
Rotate matrix around diagonals.\
54
Given an n x n matrix `M`, where n is odd and n > 1, and an integer `k`, rotate `M` counterclockwise `k` times which are not on the main diagonal or on the diagonal from the top right to the bottom left.\
55
Return the new matrix.\
56
Ex. I put *s to show which elements are fixed on the diagonals.
57
58
```
59
[*1*, 2, 3, 4, *5*]
60
[6, *7*, 8, *9*, 10]
61
[11, 12, *13*, 14, 15]
62
[16, *17*, 18, *19*, 20]
63
[*21*, 22, 23, 24, *25*]
64
65
```
66
67
Rotates to:
68
69
```
70
[*1*, 16, 11, 6, *5*]
71
[22, *7*, 12, *9*, 2]
72
[23, 18, *13*, 8, 3]
73
[24, *17*, 14, *19*, 4]
74
[*21*, 20, 15, 10, *25*]
75
76
```
77
78
Just do the obvious % 4 and then rotate a deepcopy like the LeetCode problem <https://leetcode.com/problems/rotate-image/discuss/18872/A-common-method-to-rotate-the-image>, but you check whether the element is on the diagonal before you reverse it or transpose it.
79
80
* * * * *
81
82
Medium/Hard:\
83
Given two arrays `a` and `b` of equal length, the absolute sum difference is the `sum Math.abs(a[i] - b[i])`. Replace one number in `a` with any number in `a` to minimize the absolute sum difference.
84
85
86
87
88
89
---
90
91
92
93
I tried answering all questions. Find them in serial order.\
94
I have tried giving credits wherever I used other's solution
95
96
```
97
# Author - https://leetcode.com/techdude/
98
99
# Question - 1
100
"""
101
Given an array A return an output array B of size [A.length - 2] where B[i] = 1 if sides
102
A[i],A[i+1] and A[i+2] form a triangle. Otherwise, set B[i] = 0.
103
ex. A = [1, 2, 2, 5, 5, 4] should return B = [1,0,0,1]
104
"""
105
106
A = [1, 2, 2, 5, 5, 4]
107
108
def validTriangle(A):
109
B = []; i=0
110
while i < len(A) - 2:
111
a,b,c = A[i], A[i+1], A[i+2]
112
113
if a+b>c and b+c>a and a+c>b:
114
B.append(1)
115
else:
116
B.append(0)
117
i += 1
118
return B
119
120
print(validTriangle(A))
121
print('*****************************************')
122
123
"""
124
Given two strings a and b, merge the strings so that the letters are added in alternating order
125
starting with string a. If one string is longer than the other, then append the letters to the end of the merged string.
126
ex. "abcd", "efghi" -> "aebfcgdhi"
127
ex. "", "abcd" -> "abcd"
128
ex. "abcdefg", "zxy" -> "azbxycdefg"
129
"""
130
131
a='abcd'
132
b = 'efghi'
133
134
def mergeStrings(a,b):
135
res = ''
136
for l1,l2 in zip(a,b):
137
res += l1 + l2
138
if len(a) < len(b):
139
res += b[len(a):]
140
elif len(a) > len(b):
141
res += a[len(b):]
142
return res
143
144
print(mergeStrings(a,b)) # aebfcgdhi
145
a=''; b='abcd'
146
print(mergeStrings(a,b)) # abcd
147
a="abcdefg"; b="zxy"
148
print(mergeStrings(a,b)) # azbxcydefg
149
print('*****************************************')
150
151
"""
152
Given a string s, return the longest and lexicographically smallest palindromic string
153
that can be formed from the characters.
154
155
ex. "abbaa" -> "abba"
156
ex. "adeadeadevue" -> "adeeaeeda"
157
"""
158
159
import collections
160
def smallestPalindrome(str):
161
store = collections.Counter(str)
162
lexic_store = [[key,val] for key,val in sorted(store.items(), key=lambda x:x[0]) if val > 1]
163
lexic_store_single = [[key,val] for key,val in sorted(store.items(), key=lambda x:x[0]) if val % 2 == 1][0][0]
164
165
res = ''
166
for key,val in lexic_store:
167
res += (key * int(val/2))
168
return res + lexic_store_single + res[::-1]
169
170
str = "abbaa"
171
print(smallestPalindrome(str))
172
str = "adeadeadevue"
173
print(smallestPalindrome(str))
174
175
# OP's solution - similar :)
176
177
def smallestPalindromeOP(s):
178
if not s:
179
return s
180
res = []
181
counts = collections.Counter(s)
182
alphabet = "abcdefghijklmnopqrstuvwxyz"
183
middle_letter = ""
184
for letter in alphabet:
185
count = counts.get(letter, 0)
186
if count > 0:
187
if count % 2 == 1 and middle_letter == "":
188
middle_letter = letter
189
res.append(letter * ((count - 1) // 2))
190
else:
191
res.append(letter * (count // 2))
192
193
first = "".join(res)
194
195
return first + middle_letter + first[::-1]
196
197
print(smallestPalindromeOP('abbaa'))
198
print('*****************************************')
199
200
# Easy - Medium
201
202
"""
203
Given a list of strings string_list and a list of words words, determine whether each word in words
204
can be formed as a concatenation of consecutive strings in string_list starting with index 0.
205
ex. word = "oneTwoThree", string_list = ["one", "Three", "Two"] is false because the words aren't consecutive in string_list
206
ex. word = "one", string_list = ["one", "Three", "Two"] is True because the concatenation stops at the first index in string_list
207
ex. word = "one", string_list = ["One", "one", "Two"] is False because the concatenation doesn't start at 0.
208
Just use the base idea from the LeetCode problem and then modify it for the consecutive concatenation requirement.
209
It's actually easier than the LeetCode problem.
210
"""
211
212
word = "one"; string_list = ["one", "Three", "Two"]
213
214
def isConcatenate(word, string_list):
215
res = ''
216
for w in string_list:
217
res += w
218
if res == word:
219
return True
220
return False
221
222
print(isConcatenate(word, string_list))
223
print('*****************************************')
224
225
# Medium
226
227
"""
228
Beauty of a matrix.
229
Given an n x n matrix M and an int k where n % k == 0,
230
divide the M into blocks of size k x k starting with the top left corner. i.e.
231
a 9x9 matrix turns into 9 3x3s. The beauty of a block is the smallest positive number missing
232
from a block. Rearrange M so that the blocks with the lowest beauty come before those with
233
higher beauty (top left to bottom right).
234
In a tie, you should place the block that came first in M before the other block.
235
"""
236
237
matrix = [
238
[1,2,2,3],
239
[3,4,10,4],
240
[2,10,1,2],
241
[5,4,4,5],
242
]
243
244
size = 2 # 2 x 2
245
246
def get_beauty(sub_matrix):
247
sm = sorted(sub_matrix)
248
magic_num = 1
249
for num in sm:
250
if num > magic_num:
251
return magic_num
252
magic_num += 1
253
return magic_num
254
255
def magic_number(matrix):
256
sub_matrices = []
257
serial = 0
258
for j in range(size):
259
for i in range(size):
260
x, y = j * len(matrix)//size, i * len(matrix)//size
261
262
sub_matrix = []
263
for p in range(size):
264
for q in range(size):
265
sub_matrix.append(matrix[x+p][y+q])
266
267
beauty_num = get_beauty(sub_matrix)
268
sub_matrices.append([sub_matrix, beauty_num, serial])
269
serial += 1
270
271
sub_matrices.sort(key=lambda x: (x[1],x[2]))
272
273
serial = 0
274
for j in range(size):
275
for i in range(size):
276
x, y = j * len(matrix)//size, i * len(matrix)//size
277
278
iter1 = iter(sub_matrices[serial][0])
279
for p in range(size):
280
for q in range(size):
281
matrix[x+p][y+q] = next(iter1)
282
serial += 1
283
284
for row in matrix:
285
print(row)
286
287
return matrix
288
289
magic_number(matrix)
290
291
print('*****************************************')
292
293
"""
294
Rotate matrix around diagonals.
295
Given an n x n matrix M, where n is odd and n > 1, and an integer k,
296
rotate M counterclockwise k times which are not on the main diagonal or
297
on the diagonal from the top right to the bottom left.
298
Return the new matrix.
299
Ex. I put *s to show which elements are fixed on the diagonals.
300
301
[*1*, 2, 3, 4, *5*]
302
[6, *7*, 8, *9*, 10]
303
[11, 12, *13*, 14, 15]
304
[16, *17*, 18, *19*, 20]
305
[*21*, 22, 23, 24, *25*]
306
307
Rotates to:
308
309
[*1*, 16, 11, 6, *5*]
310
[22, *7*, 12, *9*, 2]
311
[23, 18, *13*, 8, 3]
312
[24, *17*, 14, *19*, 4]
313
[*21*, 20, 15, 10, *25*]
314
"""
315
316
# Brilliant method - https://leetcode.com/problems/rotate-image/discuss/18872/A-common-method-to-rotate-the-image
317
318
# * clockwise rotate
319
# * first reverse up to down, then swap the symmetry
320
# * 1 2 3 7 8 9 7 4 1
321
# * 4 5 6 => 4 5 6 => 8 5 2
322
# * 7 8 9 1 2 3 9 6 3
323
324
matrix = [
325
[1, 2, 3, 4, 5],
326
[6, 7, 8, 9, 10],
327
[11, 12, 13, 14, 15],
328
[16, 17, 18, 19, 20],
329
[21, 22, 23, 24, 25],
330
]
331
332
def reverseImage(matrix):
333
start, end = 0, len(matrix)-1
334
335
while start < end:
336
for i in range(len(matrix)):
337
if start != i and end!= i:
338
matrix[start][i], matrix[end][i] = matrix[end][i], matrix[start][i]
339
start += 1
340
end -= 1
341
return matrix
342
343
def swapMatrix(matrix):
344
for i in range(len(matrix)):
345
for j in range(i+1, len(matrix)):
346
if i != j and i+j != len(matrix) -1:
347
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
348
return matrix
349
350
def rotateImage(matrix, num_rotate):
351
num_rotate = num_rotate % 4 # because 4 rotations = original image
352
353
for _ in range(num_rotate):
354
matrix = reverseImage(matrix)
355
matrix = swapMatrix(matrix)
356
357
return matrix
358
359
print(rotateImage(matrix, 17))
360
361
# Medium/Hard
362
"""
363
Given two arrays a and b of equal length,
364
the absolute sum difference is the sum Math.abs(a[i] - b[i]).
365
Replace one number in a with any number in a to minimize the absolute sum difference.
366
367
ref: https://leetcode.com/discuss/interview-question/949484/codesignal-gca-i-have-a-question
368
idea: https://leetcode.com/discuss/interview-question/949484/CodeSignal-GCA-(I-have-a-question)/779839
369
"""
370
371
arr1 = [1,2,3,4]
372
arr2 = [1,2,4,0]
373
374
def find_in_arr1(num, arr):
375
return min(arr, key=lambda x:abs(x[0]-num))[1]
376
377
def minAbsSumDiff(arr1, arr2):
378
sorted_arr1 = [(num,i) for i, num in enumerate(sorted(arr1))]
379
min_diff_sum = orig_sum_diff = sum([abs(num1 - num2) for num1, num2 in zip(arr1, arr2)])
380
381
for i, num in enumerate(arr1):
382
index = find_in_arr1(arr2[i], sorted_arr1)
383
if index != i:
384
min_diff_sum = min(min_diff_sum, orig_sum_diff - (abs(arr1[i]-arr2[i])) + (abs(arr1[index] - arr2[i])))
385
386
return min_diff_sum
387
388
print(minAbsSumDiff(arr1, arr2))
389
```
390
391
392
393
394
395
Python - beauty of matrix
396
397
```
398
def firstMissingPositive(nums):
399
n = len(nums)
400
401
if 1 not in nums:
402
return 1
403
404
if len(nums)==1:
405
return 2
406
407
for i, num in enumerate(nums):
408
if num<=0 or num>n:
409
nums[i] = 1
410
411
for i, num in enumerate(nums):
412
a = abs(nums[i])
413
if a==n:
414
nums[0] = -abs(nums[0])
415
else:
416
nums[a] = -abs(nums[a])
417
418
for i in range(1, len(nums)):
419
if nums[i]>0:
420
return i
421
422
if nums[0]>0:
423
return n
424
425
return n+1
426
427
def beautyOfMatrix(matrix, k):
428
n = len(matrix)
429
new_n = n//k
430
lst = [[] for j in range(new_n*new_n)]
431
432
for i in range(len(matrix)):
433
for j in range(len(matrix[0])):
434
idx = j//new_n + (i//new_n)*new_n
435
lst[idx].append(matrix[i][j])
436
437
missing =[]
438
for i in range(len(lst)):
439
mis_pos = firstMissingPositive(copy.deepcopy(lst[i]))
440
missing.append((mis_pos, i))
441
442
missing = sorted(missing)
443
444
n_box_idx = 0
445
for i in range(len(missing)):
446
box_idx = missing[i][1]
447
for j in range(len(lst[box_idx])):
448
r = (n_box_idx//new_n)*new_n + j//new_n
449
c = (n_box_idx%new_n)*new_n + j%new_n
450
matrix[r][c] = lst[box_idx][j]
451
n_box_idx += 1
452
return matrix
453
```
454
455
456
457
def max_k_occurences(sequence,word):
458
k = 1
459
while word*k in sequence:
460
k += 1
461
return k-1
462
463
l = []
464
for i in words:
465
l.append(max_k_occurences(sequence, i))
466
print l
467
468
469
470
471
472
473
474
class Solution:
475
476
def arrayShift(self, A):
477
n = len(A)
478
start = A[0]
479
cyclicShift = True
480
for a in A:
481
if a != start:
482
cyclicShift = False
483
break
484
start = (start + 1) % n
485
if start == 0:
486
start = n
487
if cyclicShift:
488
return True
489
490
start = A[0]
491
for a in A:
492
if a != start:
493
return False
494
start = (start - 1) % n
495
if start == 0:
496
start = n
497
return True
498
499
500
if __name__ == "__main__":
501
s = Solution()
502
503
A = [5, 1, 2, 3, 4]
504
print(s.arrayShift(A))
505
A = [4, 3, 2, 1, 5]
506
print(s.arrayShift(A))
507
508
A = [2, 3, 4, 5, 1]
509
print(s.arrayShift(A))
510
A = [2, 1, 5, 4, 3]
511
print(s.arrayShift(A))
512
513
A = [5, 2, 2, 3, 4]
514
print(s.arrayShift(A))
515
A = [4, 2, 2, 1, 5]
516
print(s.arrayShift(A))
517
518
519
520
521
522
523
524
525
526
527
Copied!
All CODESIGNAL
SOLUTIONS
MORE SOLUTIONS
1
def add(param1, param2):
2
return param1 + param2
3
def centuryFromYear(year):
4
return ((year-1) // 100) + 1
5
6
def checkPalindrome(inputString):
7
return inputString == inputString[::-1]
8
9
def adjacentElementsProduct(inputArray):
10
max = inputArray[0] * inputArray[1]
11
for i in range(len(inputArray) - 1):
12
if inputArray[i] * inputArray[i+1] > max:
13
max = inputArray[i] * inputArray[i+1]
14
return max
15
16
def shapeArea(n):
17
sum = n*2 - 1
18
for i in range(1, (n*2)-1, 2):
19
sum += i*2
20
return sum
21
def makeArrayConsecutive2(statues):
22
return max(statues) - min(statues) - len(statues) + 1
23
def almostIncreasingSequence(sequence):
24
i = 0
25
while i < len(sequence) - 1:
26
if not sequence[i] < sequence[i + 1]:
27
if increasingSequence(sequence[:i] + sequence[i+1:]) or \
28
increasingSequence(sequence[:i+1] + sequence[i+2:]):
29
return True
30
else:
31
return False
32
i += 1
33
return True
34
35
36
def increasingSequence(sequence):
37
for i in range(len(sequence) - 1):
38
if not sequence[i] < sequence[i + 1]:
39
return False
40
return True
41
42
def matrixElementsSum(matrix):
43
if len(matrix) > 1:
44
for row in range(1, len(matrix)):
45
for room in range(len(matrix[row])):
46
if matrix[row - 1][room] == 0:
47
matrix[row][room] = 0
48
sum = 0
49
for row in matrix:
50
for room in row:
51
sum += room
52
return sum
53
54
def allLongestStrings(inputArray):
55
length = max([len(word) for word in inputArray])
56
result = [word for word in inputArray if len(word) == length]
57
return result
58
def commonCharacterCount(s1, s2):
59
count = 0
60
word2 = list(s2)
61
for letter in s1:
62
if letter in word2:
63
word2.remove(letter)
64
count += 1
65
return count
66
67
def isLucky(n):
68
string = str(n)
69
top = [int(x) for x in string[:len(string)//2]]
70
bottom = [int(x) for x in string[len(string)//2:]]
71
return sum(top) == sum(bottom)
72
def sortByHeight(a):
73
treePositions = [x for x in range(len(a)) if a[x] == -1]
74
people = sorted([x for x in a if x != -1])
75
for tree in treePositions:
76
people.insert(tree, -1)
77
return people
78
79
import re
80
def reverseParentheses(s):
81
while "(" in s:
82
match = re.search("\([^()]*\)", s)
83
match_string = match.group(0)[1: len(match.group(0)) - 1]
84
reversed_match_string = match_string[::-1]
85
s = s[:match.start()] + reversed_match_string + s[match.end():]
86
return s
87
88
def alternatingSums(a):
89
team1 = sum(a[0::2])
90
team2 = sum(a[1::2])
91
return [team1, team2]
92
def addBorder(picture):
93
picture = ["*" + string + "*" for string in picture]
94
picture = [("*" * len(picture[0]))] + picture + [("*" * len(picture[0]))]
95
return picture
96
97
def areSimilar(a, b):
98
diff = [i for i in range(len(a)) if a[i] != b[i]]
99
if len(diff) == 2:
100
b[diff[0]], b[diff[1]] = b[diff[1]], b[diff[0]]
101
return a == b
102
103
def arrayChange(inputArray):
104
count = 0
105
for i in range(1, len(inputArray)):
106
if inputArray[i-1] >= inputArray[i]:
107
difference = inputArray[i-1] - inputArray[i]
108
inputArray[i] += difference + 1
109
count += difference + 1
110
return count
111
112
def palindromeRearranging(inputString):
113
inputList = sorted(inputString)
114
foundMiddle = False
115
while len(inputList) > 1:
116
if inputList[0] == inputList[1]:
117
del inputList[1]
118
elif not foundMiddle:
119
foundMiddle = True
120
else:
121
return False
122
del inputList[0]
123
return len(inputList) == 0 or not foundMiddle
124
125
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
126
sameHands = yourLeft == friendsLeft and yourRight == friendsRight
127
differentHands = yourLeft == friendsRight and yourRight == friendsLeft
128
return sameHands or differentHands
129
130
def arrayMaximalAdjacentDifference(inputArray):
131
diffs = []
132
for i in range(len(inputArray) - 1):
133
diffs.append(abs(inputArray[i] - inputArray[i + 1]))
134
return max(diffs)
135
136
def isIPv4Address(inputString):
137
strings = [string for string in inputString.split('.')]
138
for string in strings:
139
if not string.isdecimal():
140
return False
141
nums = [int(num) for num in strings]
142
return max(nums) <= 255 and min(nums) >= 0 and len(nums) == 4
143
144
def avoidObstacles(inputArray):
145
for length in range(2, max(inputArray) + 2):
146
done = True
147
jump = length
148
while jump < (max(inputArray) + length):
149
if jump in inputArray:
150
done = False
151
break
152
jump += length
153
if done:
154
return length
155
156
def boxBlur(image):
157
outImage = []
158
for row in range(1, len(image) - 1):
159
line = []
160
for pixel in range(1, len(image[row]) - 1):
161
total = (image[row - 1][pixel - 1]
162
+ image[row - 1][pixel]
163
+ image[row - 1][pixel + 1]
164
+ image[row][pixel - 1]
165
+ image[row][pixel]
166
+ image[row][pixel + 1]
167
+ image[row + 1][pixel - 1]
168
+ image[row + 1][pixel]
169
+ image[row + 1][pixel + 1])
170
line.append(total // 9)
171
outImage.append(line)
172
return outImage
173
174
def minesweeper(matrix):
175
TOP = 0
176
BOTTOM = len(matrix) - 1
177
LEFT = 0
178
RIGHT = len(matrix[0]) - 1
179
180
outMatrix = []
181
for row in range(len(matrix)):
182
outRow = []
183
for cell in range(len(matrix[row])):
184
outRow.append(0)
185
if row != TOP:
186
outRow[cell] += matrix[row - 1][cell]
187
if row != BOTTOM:
188
outRow[cell] += matrix[row + 1][cell]
189
if cell != LEFT:
190
outRow[cell] += matrix[row][cell - 1]
191
if cell != RIGHT:
192
outRow[cell] += matrix[row][cell + 1]
193
if row != TOP and cell != LEFT:
194
outRow[cell] += matrix[row - 1][cell - 1]
195
if row != TOP and cell != RIGHT:
196
outRow[cell] += matrix[row - 1][cell + 1]
197
if row != BOTTOM and cell != LEFT:
198
outRow[cell] += matrix[row + 1][cell - 1]
199
if row != BOTTOM and cell != RIGHT:
200
outRow[cell] += matrix[row + 1][cell + 1]
201
outMatrix.append(outRow)
202
return outMatrix
203
204
def arrayReplace(inputArray, elemToReplace, substitutionElem):
205
return [x if x != elemToReplace else substitutionElem for x in inputArray]
206
207
def evenDigitsOnly(n):
208
return all((True if digit in ('0', '2', '4', '6', '8') else False for digit in str(n)))
209
210
def variableName(name):
211
return name.replace("_", "").isalnum() and not name[0].isdigit()
212
213
def alphabeticShift(inputString):
214
return ''.join([chr(ord(x) + 1) if x != 'z' else 'a' for x in inputString])
215
216
def chessBoardCellColor(cell1, cell2):
217
color1 = ((ord(cell1[0]) - ord('A')) + ord(cell1[1]) - ord('1')) % 2 == 0
218
color2 = ((ord(cell2[0]) - ord('A')) + ord(cell2[1]) - ord('1')) % 2 == 0
219
return color1 == color2
220
221
def circleOfNumbers(n, firstNumber):
222
return (firstNumber + (n / 2)) % n
223
224
def depositProfit(deposit, rate, threshold):
225
year = 0
226
while deposit < threshold:
227
deposit *= 1 + (rate / 100)
228
year += 1
229
return year
230
231
def absoluteValuesSumMinimization(a):
232
sums = {}
233
for num in a:
234
total = sum([abs(a[i] - num) for i in range(len(a))])
235
if total in sums:
236
sums[total] = min(num, sums[total])
237
else:
238
sums[total] = num
239
print(sums)
240
return sums[min(sums)]
241
242
import itertools
243
244
def stringsRearrangement(inputArray):
245
permutations = itertools.permutations(inputArray)
246
for array in permutations:
247
if testArrangement(array):
248
return True
249
return False
250
251
def testArrangement(array):
252
for i in range(len(array) - 1):
253
if sum([a != b for a, b in zip(array[i], array[i + 1])]) != 1:
254
return False
255
return True
256
257
def extractEachKth(inputArray, k):
258
return [inputArray[x] for x in range(len(inputArray)) if (x + 1) % k != 0]
259
260
def firstDigit(inputString):
261
for char in inputString:
262
if char.isdigit():
263
return char
264
265
def differentSymbolsNaive(s):
266
return len(set(s))
267
268
def arrayMaxConsecutiveSum(inputArray, k):
269
sums = [sum(inputArray[:k])]
270
for i in range(1, len(inputArray) - k + 1):
271
sums.append(sums[i - 1] - inputArray[i - 1] + inputArray[i + k - 1])
272
return max(sums)
273
274
def growingPlant(upSpeed, downSpeed, desiredHeight):
275
height = 0
276
days = 1
277
height += upSpeed
278
while height < desiredHeight:
279
days += 1
280
height -= downSpeed
281
height += upSpeed
282
return days
283
284
def knapsackLight(value1, weight1, value2, weight2, maxW):
285
if weight1 + weight2 <= maxW:
286
return value1 + value2
287
if weight1 <= maxW and (weight2 > maxW or value1 >= value2):
288
return value1
289
if weight2 <= maxW and (weight1 > maxW or value2 >= value1):
290
return value2
291
return 0
292
293
def longestDigitsPrefix(inputString):
294
for char in range(len(inputString)):
295
if not inputString[char].isdigit():
296
return inputString[:char]
297
return inputString
298
299
def digitDegree(n):
300
degree = 0
301
while len(str(n)) > 1:
302
n = sum((int(digit) for digit in str(n)))
303
degree += 1
304
return degree
305
306
def bishopAndPawn(bishop, pawn):
307
return abs(ord(bishop[0]) - ord(pawn[0])) == abs(ord(bishop[1]) - ord(pawn[1]))
308
309
def isBeautifulString(inputString):
310
for letter in range(ord('a'), ord('z')):
311
if inputString.count(chr(letter)) < inputString.count(chr(letter + 1)):
312
return False
313
return True
314
315
def findEmailDomain(address):
316
return address[address.rfind('@') + 1:]
317
318
def buildPalindrome(st):
319
if st == st[::-1]: # Check for initial palindrome
320
return st
321
index = 0
322
subStr = st[index:]
323
while subStr != subStr[::-1]: # while substring is not a palindrome
324
index += 1
325
subStr = st[index:]
326
return st + st[index - 1::-1]
327
328
def electionsWinners(votes, k):
329
winners = 0
330
current_winner = max(votes)
331
for candidate in votes:
332
if k > 0 and candidate + k > current_winner:
333
winners += 1
334
if k == 0 and candidate == current_winner and votes.count(candidate) == 1:
335
winners += 1
336
return winners
337
338
def isMAC48Address(inputString):
339
hex_chars = ('1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
340
'A', 'B', 'C', 'D', 'E', 'F',
341
'a', 'b', 'c', 'd', 'e', 'f')
342
groups = inputString.split('-')
343
if len(groups) != 6:
344
return False
345
if not all((len(group) == 2 for group in groups)):
346
return False
347
if not all((group[0] in hex_chars and group[1] in hex_chars for group in groups)):
348
return False
349
return True
350
351
def isDigit(symbol):
352
return symbol.isdigit()
353
354
def lineEncoding(s):
355
count = 1
356
output = []
357
for char in range(1, len(s)):
358
if s[char] == s[char - 1]:
359
count += 1
360
else:
361
if count > 1:
362
output.append(str(count) + s[char - 1])
363
else:
364
output.append(s[char - 1])
365
count = 1
366
if s[len(s) - 1] == s[len(s) - 2]:
367
output.append(str(count) + s[len(s) - 1])
368
else:
369
output.append(s[len(s) - 1])
370
return ''.join(output)
371
372
def chessKnight(cell):
373
moves = 0
374
# Starting at the top left, going counter-clockwise
375
if ord(cell[0]) >= ord("b") and ord(cell[1]) <= ord("6"):
376
moves += 1
377
if ord(cell[0]) >= ord("c") and ord(cell[1]) <= ord("7"):
378
moves += 1
379
if ord(cell[0]) >= ord("c") and ord(cell[1]) >= ord("2"):
380
moves += 1
381
if ord(cell[0]) >= ord("b") and ord(cell[1]) >= ord("3"):
382
moves += 1
383
if ord(cell[0]) <= ord("g") and ord(cell[1]) >= ord("3"):
384
moves += 1
385
if ord(cell[0]) <= ord("f") and ord(cell[1]) >= ord("2"):
386
moves += 1
387
if ord(cell[0]) <= ord("f") and ord(cell[1]) <= ord("7"):
388
moves += 1
389
if ord(cell[0]) <= ord("g") and ord(cell[1]) <= ord("6"):
390
moves += 1
391
392
return moves
393
394
def deleteDigit(n):
395
num = str(n)
396
highest = 0
397
for digit in range(len(num)):
398
output = num[:digit] + num[digit + 1:]
399
if int(output) > int(highest):
400
highest = output
401
return int(highest)
402
403
def longestWord(text):
404
longest = []
405
word = []
406
for char in text:
407
if ord("A") <= ord(char) <= ord("Z") or ord("a") <= ord(char) <= ord("z"):
408
word.append(char)
409
else:
410
if len(word) > len(longest):
411
longest = word
412
word = []
413
if len(word) > len(longest):
414
longest = word
415
return "".join(longest)
416
def validTime(time):
417
groups = time.split(":")
418
if len(groups) != 2:
419
return False
420
if not (groups[0].isdigit() and groups[1].isdigit()):
421
return False
422
if int(groups[0]) > 23 or int(groups[1]) > 59:
423
return False
424
return True
425
426
def sumUpNumbers(inputString):
427
total = 0
428
current_num = []
429
for char in inputString:
430
if char.isdigit():
431
current_num.append(char)
432
else:
433
if len(current_num) > 0:
434
num = int("".join(current_num))
435
total += num
436
current_num = []
437
if len(current_num) > 0:
438
num = int("".join(current_num))
439
total += num
440
return total
441
442
def differentSquares(matrix):
443
squares = set()
444
for row in range(len(matrix) - 1):
445
for cell in range(len(matrix[row]) - 1):
446
square = ((matrix[row][cell], matrix[row][cell + 1]),
447
(matrix[row + 1][cell], matrix[row + 1][cell + 1]))
448
squares.add(square)
449
return len(squares)
450
451
def digitsProduct(product):
452
# New idea: add product to factors
453
# while max(factors) > 10: split that num into factors
454
if product == 0:
455
return 10
456
457
factors = [product]
458
while max(factors) > 9:
459
factored = findFactors(max(factors))
460
if factored:
461
factors.remove(max(factors))
462
factors.extend(factored)
463
else:
464
return -1
465
466
while factors.count(3) >= 2:
467
factors.remove(3)
468
factors.remove(3)
469
factors.append(9)
470
471
while factors.count(2) > 2:
472
factors.remove(2)
473
factors.remove(2)
474
factors.remove(2)
475
factors.append(8)
476
477
while factors.count(2) > 1:
478
factors.remove(2)
479
factors.remove(2)
480
factors.append(4)
481
482
while 2 in factors and 3 in factors:
483
factors.remove(2)
484
factors.remove(3)
485
factors.append(6)
486
487
return int("".join(map(str, sorted(factors))))
488
489
490
def findFactors(n):
491
for i in range(2, int(n ** 0.5) + 1):
492
if n % i == 0:
493
return i, n // i
494
return False
495
496
def fileNaming(names):
497
outnames = []
498
for name in names:
499
if name in outnames:
500
k = 1
501
while "{}({})".format(name, k) in outnames:
502
k += 1
503
name = "{}({})".format(name, k)
504
outnames.append(name)
505
return outnames
506
507
def messageFromBinaryCode(code):
508
output = []
509
for i in range(0, len(code), 8):
510
letter = chr(int(code[i:i + 8], 2))
511
output.append(letter)
512
return ''.join(output)
513
514
def spiralNumbers(n):
515
LEFT = 'left'
516
RIGHT = 'right'
517
UP = 'up'
518
DOWN = 'down'
519
direction = RIGHT
520
spiral = [[0 for i in range(n)] for j in range(n)]
521
row = 0
522
cell = 0
523
for num in range(1, (n * n) + 1):
524
spiral[row][cell] = num
525
if direction == RIGHT:
526
if cell != n - 1 and spiral[row][cell + 1] == 0:
527
cell += 1
528
else:
529
direction = DOWN
530
row += 1
531
elif direction == DOWN:
532
if row != n - 1 and spiral[row + 1][cell] == 0:
533
row += 1
534
else:
535
direction = LEFT
536
cell -= 1
537
elif direction == LEFT:
538
if cell != 0 and spiral[row][cell - 1] == 0:
539
cell -= 1
540
else:
541
direction = UP
542
row -= 1
543
elif direction == UP:
544
if row != 0 and spiral[row - 1][cell] == 0:
545
row -= 1
546
else:
547
direction = RIGHT
548
cell += 1
549
return spiral
550
551
552
print(spiralNumbers(5))
553
554
def sudoku(grid):
555
match = [i for i in range(1, 10)]
556
for row in grid:
557
if sorted(row) != match:
558
return False
559
for column_index in range(9):
560
column = [grid[row_index][column_index] for row_index in range(9)]
561
if sorted(column) != match:
562
return False
563
for row in range(0, 9, 3):
564
for column in range(0, 9, 3):
565
box = []
566
box.extend(grid[row][column:column + 3])
567
box.extend(grid[row + 1][column:column + 3])
568
box.extend(grid[row + 2][column:column + 3])
569
if sorted(box) != match:
570
return False
571
return True
572
573
# def isAdult(age, majority):
574
# return age >= majority
575
576
isAdult = lambda a, m: a >= m
577
578
def bishopAndPawn(bishop, pawn):
579
if ord(bishop[0]) == ord(pawn[0]):
580
return False
581
else:
582
bishop_elm = ord(bishop[0]) + int(bishop[1])
583
pawn_elm = ord(pawn[0]) + int(pawn[1])
584
return (bishop_elm + pawn_elm) % 2 == 0
585
586
"""Below we will define an n-interesting polygon. Your task is to find the area of a polygon for a given n.
587
A 1-interesting polygon is just a square with a side of length 1. An n-interesting polygon is obtained by taking the
588
(n - 1)-interesting polygon and appending 1-interesting polygons to its rim, side by side.
589
You can see the 1-, 2-, 3- and 4-interesting polygons in the picture below. (PICTURE PROVIDED AT:WWW.CODESIGNAL.COM)
590
591
Example:
592
- For n = 2, the output should be shapeArea(n) = 5;
593
- For n = 3, the output should be shapeArea(n) = 13."""
594
595
596
def shapeArea(n):
597
# Case 1: If the polygon is 0-interesting, it has an area equal to zero.
598
if n == 0:
599
return None
600
# Case 2: If the polygon is 1-interesting, it has an area equal to one.
601
elif n == 1:
602
return 1
603
# Case 3: If the polygon is n-interesting, it has an area equal to the sum of the square of n
604
# and the square of n-1. A way that I thought of it (based on the picture provided) is the following:
605
# - n**2: Counted the number of the blue squares from the middle line upwards (INCLUDING the blue squares of the middle line).
606
# - (n-1)**2: Counted the number of the blue squares from the middle line downwards (EXCLUDING the blue squares of the middle line).
607
# Of course, you can easily check that the terms "upwards/downwards" could be inverted, without affecting the validity of your counting.
608
elif n > 1:
609
result = (n ** 2) + ((n - 1) ** 2)
610
return result
611
612
"""Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size.
613
Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the
614
previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of
615
additional statues needed.
616
617
Example:
618
For statues = [6, 2, 3, 8], the output should be makeArrayConsecutive2(statues) = 3.
619
Ratiorg needs statues of sizes 4, 5 and 7."""
620
621
622
def makeArrayConsecutive2(statues):
623
# Step 1: We begin by creating a new array called "stat_arr", which will accommodate the sorted version of the original "statues" array.
624
stat_arr = sorted(statues)
625
# Step 2: Furthermore, we use the first element of the sorted array as our index (that will be used in the following steps).
626
i = stat_arr[0]
627
# Step 3: We create an empty list called "result" to store our (numbered) missing statues.
628
result = list()
629
# Step 4: We initiate a while-loop with the condition that the index from Step 2 is not equal to the last (hence largest) entry of
630
# the stat_arr. You must make sure that you add the "incrementation by 1" part to make the while loop proceed to the next element.
631
while i != stat_arr[-1]:
632
i += 1
633
# Step 5: Here, using a simple if statement, we examine whether the i-th (integer) element is included in the stat_arr.
634
# If it is not, we append it to the result list. Otherwise, the loop continues.
635
if i not in stat_arr:
636
result.append(i)
637
else:
638
continue
639
# Step 6: Finally, we return the length/size of the result list, i.e. the number of our "missing" statues.
640
return len(result)
641
642
a, b = eval(dir()[0])
643
return a + b
644
645
# 28
646
# return sum(eval(dir()[0]), [])
647
648
# 36
649
# return [x for l in eval(dir()[0]) for x in l]
650
651
# def twoArraysNthElement(array1, array2, n):
652
# return sorted(array1 + array2)[n]
653
# 70
654
655
# twoArraysNthElement = lambda a, b, n: sorted(a + b)[n]
656
# 46
657
658
a, b, n = eval(dir()[0])
659
return sorted(a + b)[n]
660
# 40
661
662
n, d = eval(dir()[0])
663
while n % d < 1:
664
n /= d
665
return n
666
667
# def divideAsLongAsPossible(n, d):
668
# while n % d == 0:
669
# n /= d
670
# return n
671
672
class TreeNode:
673
def __init__(self, x):
674
self.val = x
675
self.left = None
676
self.right = None
677
678
679
class Solution:
680
def bstFromPreorder(self, preorder):
681
if not preorder:
682
return None
683
root = TreeNode(preorder[0])
684
i = 1
685
while i < len(preorder) and preorder[i] < root.val:
686
i += 1
687
root.left = self.bstFromPreorder(preorder[1:i])
688
root.right = self.bstFromPreorder(preorder[i:])
689
return root
690
691
692
preorder = [19, 4, 8, 11]
693
bst = Solution()
694
bst.bstFromPreorder(preorder)
695
696
def isBeautifulString(inputString):
697
counter = [inputString.count(i) for i in string.ascii_lowercase]
698
return counter[::-1] == sorted(counter)
699
700
def boxBlur(image):
701
def pixels(matrix, i, j):
702
summ = 0
703
for x in range(i - 1, i + 2):
704
for y in range(j - 1, j + 2):
705
summ += matrix[x][y]
706
mean = summ // 9
707
return mean
708
709
output = []
710
row = len(image)
711
col = len(image[0])
712
for i in range(1, row - 1):
713
arr = []
714
for j in range(1, col - 1):
715
arr.append(pixels(image, i, j))
716
output.append(arr)
717
return output
718
719
def chessBoardCellColor(cell1, cell2):
720
cell1_elm = ord(cell1[0]) + int(cell1[1])
721
cell2_elm = ord(cell2[0]) + int(cell2[1])
722
return (cell1_elm + cell2_elm) % 2 == 0
723
724
def addBorder(picture):
725
new_pic = []
726
border = ""
727
pic_len = len(picture)
728
for i in range(0, len(picture[0]) + 2):
729
border += "*"
730
new_pic.append(border)
731
for i in range(0, pic_len):
732
new_pic.append("*" + picture[i] + "*")
733
new_pic.append(border)
734
return new_pic
735
736
sulkyBoy = lambda x: not x
737
738
import itertools as i
739
740
# *re.findall('...', 'abcdefghijklmno')
741
# >>> 'abc', 'def', 'ghi', 'jkl', 'mno'
742
743
#  [0,0,"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
744
return [
745
"".join(s)
746
for s in i.product(
747
*[
748
"0 0 abc def ghi jkl mno pqrs tuv wxyz".split()[int(i)]
749
for i in eval(dir()[0])[0]
750
]
751
)
752
if s
753
]
754
755
def maxProfit(prices):
756
i = 0
757
max_profit = 0
758
while i < len(prices) - 1:
759
while i < len(prices) - 1 and prices[i] >= prices[i + 1]:
760
i += 1
761
min_pri = prices[i]
762
while i < len(prices) - 1 and prices[i] <= prices[i + 1]:
763
i += 1
764
max_pri = prices[i]
765
max_profit += max_pri - min_pri
766
return max_profit
767
768
769
print(maxProfit([1, 2, 3, 4, 5, 6]))
770
771
A, = numpy.r_[eval(dir()[0])]
772
A[A > 0] = sorted(A[A > 0])
773
return A
774
775
"""Some people are standing in a row in a park. There are trees between them which cannot be moved.
776
Your task is to rearrange the people by their heights in a non-descending order without moving the trees.
777
People can be very tall!
778
779
Example:
780
- For a = [-1, 150, 190, 170, -1, -1, 160, 180], the output should be sortByHeight(a) = [-1, 150, 160, 170, -1, -1, 180, 190]."""
781
782
783
def sortByHeight(a):
784
# Step 1: We begin by creating a counter, starting from 0, that will be used in the subsequent for-loop.
785
j = 0
786
# Step 2: We also create a new array, called "a_sort", where we sort (in ascending order) all elements of the given array "a"
787
# that are not "trees" (i.e. do not have a value of -1).
788
a_sort = sorted([i for i in a if i != -1])
789
# Step 3: By implementing a for-loop, we investigate all elements of the given array "a" (NOT a_sort!) and check:
790
# if the element i in array "a" is equal to -1, the for-loop continues. Otherwise, the element i in array "a" should be
791
# the same as element j in array "a_sort" (starting from 0 index, as defined in step 1).
792
# You can think of it as working through elements of array "a", disregarding the "trees" (-1s) and sorting the rest
793
# of the elements in ascending order (as in a_sort).
794
for i in range(len(a)):
795
if a[i] == -1:
796
pass
797
else:
798
a[i] = a_sort[j]
799
j += 1
800
# Step 4: The final step is the return of the modified array "a".
801
return a
802
803
def arrayChange(inputArray):
804
first = inputArray[0]
805
count = 0
806
for i in inputArray[1:]:
807
if i <= first:
808
count += first - i + 1
809
first = first + 1
810
else:
811
first = i
812
return count
813
814
"""Given two strings, find the number of common characters between them.
815
816
Example:
817
For s1 = "aabcc" and s2 = "adcaa", the output should be commonCharacterCount(s1, s2) = 3.
818
Strings have 3 common characters - 2 "a"s and 1 "c"."""
819
820
821
def commonCharacterCount(s1, s2):
822
# Step 1: We create two lists, namely s1_l and s2_l, where we store the characters of strings s1 and s2 respectively.
823
s1_l = list(s1)
824
s2_l = list(s2)
825
# Step 2: We also create an empty list, where we are going to store all common characters.
826
common = []
827
# Step 3: Using a for-loop, we investigate the list of the first string, element by element.
828
for i in s1_l:
829
# Step 4: If the i-th element from the list of the first string is also present in the list of the second string,
830
# we append it to the common array. BE CAREFUL: We must implement the s2_l.remove(i) to avoid double-counting.
831
# I checked myself and I can assure you that you can substitute s1_l for s2_l and vice versa (in the for-loop,
832
# the if statement and the double-counting term), without affecting the validity of your code.
833
if i in s2_l:
834
common.append(i)
835
s2_l.remove(i)
836
# Step 5: Finally, we return the length of the common list, to find the number of the common characters
837
# between the two strings given.
838
return len(common)
839
840
# def passwordCheck(s):
841
# if any(i.isdigit() for i in s) and any(i.islower() for i in s) and any(i.isupper() for i in s) and len(s) >= 5:
842
# return True
843
# else:
844
# return False
845
846
# passwordCheck = lambda s: (any(i.isdigit()) and any(i.islower()) and any(i.isupper())) for i in s and len(s) > 4
847
848
# Regex:
849
850
# def passwordCheck(s):
851
# return len(s) > 4 and all(re.search(p, s) for p in ('[A-Z]', '\d', '[a-z]'))
852
853
passwordCheck = lambda s: len(s) > 4 and all(
854
re.search(i, s) for i in ("[A-Z]", "\d", "[a-z]")
855
)
856
857
# def fractionComparison(a, b):
858
# d = a[0] / a[1]
859
# f = b[0] / b[1]
860
# if d < f:
861
# return "<"
862
# elif d > f:
863
# return ">"
864
# else:
865
# return "="
866
867
(a, b), (c, d) = eval(dir()[0])
868
r = (a * d) / (b * c)
869
return "<" if r < 1 else ">" if r > 1 else "="
870
871
# 72 chars
872
873
# Nique toi Sylvere
874
875
L, = eval(dir()[0])
876
s = 0
877
878
879
while len(L) > 1:
880
L = (
881
numpy.add(L[:-1:2], L[1::2])
882
if s % 2 == 0
883
else numpy.multiply(L[:-1:2], L[1::2])
884
)
885
s += 1
886
887
return L[0]
888
889
L, = eval(dir()[0])
890
s = 0
891
892
893
while len(L) > 1:
894
L = (
895
numpy.add(L[:-1:2], L[1::2])
896
if s % 2 == 0
897
else numpy.multiply(L[:-1:2], L[1::2])
898
)
899
s += 1
900
901
return L[0]
902
903
def addTwoDigits(n):
904
return (n // 10) + (n % 10)
905
def largestNumber(n):
906
return int("9" * n)
907
908
def candies(n, m):
909
return (m // n) * n
910
911
def seatsInTheater(nCols, nRows, col, row):
912
return (nCols - col + 1) * (nRows - row)
913
914
def maxMultiple(divisor, bound):
915
for num in range(bound, 1, -1):
916
if num % divisor == 0:
917
return num
918
return 0
919
920
def circleOfNumbers(n, firstNumber):
921
return (firstNumber + (n // 2)) % n
922
923
def lateRide(n):
924
hours = n // 60
925
minutes = n % 60
926
return (hours // 10) + (hours % 10) + (minutes // 10) + (minutes % 10)
927
928
def phoneCall(min1, min2_10, min11, s):
929
if s < min1:
930
return 0
931
if s == min1:
932
return 1
933
if s <= min1 + (min2_10 * 9):
934
s -= min1
935
return (s // min2_10) + 1
936
s -= min1
937
s -= min2_10 * 9
938
return (s // min11) + 10
939
940
def reachNextLevel(experience, threshold, reward):
941
return experience + reward >= threshold
942
943
def knapsackLight(value1, weight1, value2, weight2, maxW):
944
if weight1 + weight2 <= maxW:
945
return value1 + value2
946
if weight1 <= maxW and weight2 <= maxW:
947
return max(value1, value2)
948
if weight1 <= maxW:
949
return value1
950
if weight2 <= maxW:
951
return value2
952
return 0
953
954
def extraNumber(a, b, c):
955
if a == b:
956
return c
957
if a == c:
958
return b
959
return a
960
961
def isInfiniteProcess(a, b):
962
return a > b or (a % 2 != b % 2)
963
964
def arithmeticExpression(a, b, c):
965
return a + b == c or a - b == c or a * b == c or a / b == c
966
967
def tennisSet(score1, score2):
968
if max(score1, score2) == 6 and min(score1, score2) < 5:
969
return True
970
if 5 <= min(score1, score2) <= 6 and max(score1, score2) == 7:
971
return True
972
return False
973
974
def willYou(young, beautiful, loved):
975
return (young and beautiful) != loved
976
977
def metroCard(lastNumberOfDays):
978
if lastNumberOfDays == 30 or lastNumberOfDays == 28:
979
return [31]
980
return [28, 30, 31]
981
982
def killKthBit(n, k):
983
return n & ~(2 ** (k - 1))
984
985
def arrayPacking(a):
986
binary_array = [bin(num)[2:].rjust(8, '0') for num in a]
987
out_string = ''.join(binary_array[::-1])
988
return int(out_string, 2)
989
990
def rangeBitCount(a, b):
991
array = list(range(a, b + 1))
992
binary_array = [bin(num) for num in array]
993
count_array = [binary.count('1') for binary in binary_array]
994
return sum(count_array)
995
996
def mirrorBits(a):
997
binary = bin(a)[2:]
998
return int(binary[::-1], 2)
999
1000
def secondRightmostZeroBit(n):
1001
return 2 ** bin(n)[::-1].find('0', bin(n)[::-1].find('0') + 1)
1002
1003
def swapAdjacentBits(n):
1004
return ((n >> 1) & 1431655765) | ((n << 1) & 2863311530)
1005
1006
def differentRightmostBit(n, m):
1007
return 2 ** bin((n ^ m))[::-1].find('1')
1008
1009
def equalPairOfBits(n, m):
1010
return 2 ** bin(~(n ^ m))[::-1].find('1')
1011
1012
def leastFactorial(n):
1013
factorial = 1
1014
index = 1
1015
while factorial < n:
1016
index += 1
1017
factorial *= index
1018
return factorial
1019
1020
def countSumOfTwoRepresentations2(n, l, r):
1021
count = 0
1022
a = max(n - r, l)
1023
b = n - a
1024
while a <= r and a <= b:
1025
count += 1
1026
a += 1
1027
b -= 1
1028
return count
1029
1030
def magicalWell(a, b, n):
1031
total = 0
1032
for i in range(n):
1033
total += a * b
1034
a += 1
1035
b += 1
1036
return total
1037
1038
def lineUp(commands):
1039
count = 0
1040
smart_student = 0
1041
dumb_student = 0
1042
for command in commands:
1043
if command == 'L':
1044
smart_student = (smart_student - 1) % 4
1045
dumb_student = (dumb_student + 1) % 4
1046
elif command == 'R':
1047
smart_student = (smart_student + 1) % 4
1048
dumb_student = (dumb_student - 1) % 4
1049
elif command == 'A':
1050
smart_student = (smart_student + 2) % 4
1051
dumb_student = (dumb_student + 2) % 4
1052
1053
if smart_student == dumb_student:
1054
count += 1
1055
return count
1056
1057
def additionWithoutCarrying(param1, param2):
1058
# Convert numbers to strings
1059
str1 = str(param1)
1060
str2 = str(param2)
1061
# Pad both to the same length with zeroes (to the left of the numbers)
1062
length = max(len(str2), len(str1))
1063
str1 = str1.rjust(length, '0')
1064
str2 = str2.rjust(length, '0')
1065
output = []
1066
for num1, num2 in zip(str1, str2):
1067
result = str(int(num1) + int(num2))[-1]
1068
output.append(result)
1069
return int(''.join(output))
1070
1071
def appleBoxes(k):
1072
red = 0
1073
yellow = 0
1074
for i in range(1, k + 1, 2):
1075
yellow += i * i
1076
for i in range(2, k + 1, 2):
1077
red += i * i
1078
1079
return red - yellow
1080
1081
def increaseNumberRoundness(n):
1082
string = str(n)
1083
# Check for immediate rejection
1084
if '0' not in string or len(string) < 2:
1085
return False
1086
# Since we know there's a 0, if it's not on
1087
# the left, then we know to accept
1088
if string[-1] != '0':
1089
return True
1090
# If there is only one 0, it must be at the end, so reject.
1091
if string.count('0') == 1:
1092
return False
1093
# If there are any numbers between the first 0
1094
# and the end of the string, then accept.
1095
first_zero = string.find('0')
1096
zero_sandwich = string[first_zero:]
1097
return zero_sandwich.count('0') != len(zero_sandwich)
1098
1099
def rounders(value):
1100
length = len(str(value))
1101
magnitude = length - 1
1102
for i in range(length - 1):
1103
value = int((value / 10) + 0.5)
1104
return value * (10 ** magnitude)
1105
1106
def candles(candlesNumber, makeNew):
1107
totalBurned = 0
1108
leftovers = 0
1109
while candlesNumber > 0:
1110
totalBurned += candlesNumber
1111
leftovers += candlesNumber
1112
candlesNumber = 0
1113
candlesNumber = leftovers // makeNew
1114
leftovers = leftovers % makeNew
1115
return totalBurned
1116
1117
def countBlackCells(n, m):
1118
gcd = find_gcd(n, m)
1119
line_cells = n + m - gcd
1120
line_corner_cells = (gcd - 1) * 2
1121
return line_cells + line_corner_cells
1122
1123
1124
def find_gcd(a, b):
1125
while b != 0:
1126
a, b = b, a % b
1127
return a
1128
1129
def createArray(size):
1130
return [1] * size
1131
1132
def arrayReplace(inputArray, elemToReplace, substitutionElem):
1133
output = [elem if elem != elemToReplace else substitutionElem for elem in inputArray]
1134
return output
1135
def firstReverseTry(arr):
1136
if len(arr) < 2:
1137
return arr
1138
if len(arr) < 4:
1139
return arr[::-1]
1140
return arr[-1:] + arr[1:-1] + arr[:1]
1141
1142
def concatenateArrays(a, b):
1143
return a + b
1144
1145
def removeArrayPart(inputArray, l, r):
1146
return inputArray[:l] + inputArray[r + 1:]
1147
1148
def isSmooth(arr):
1149
if arr[0] != arr[-1]:
1150
return False
1151
if len(arr) % 2 == 0:
1152
middle = arr[len(arr) // 2] + arr[(len(arr) // 2) - 1]
1153
else:
1154
middle = arr[len(arr) // 2]
1155
return arr[0] == middle
1156
def replaceMiddle(arr):
1157
if len(arr) % 2 != 0:
1158
return arr
1159
right_middle = len(arr) // 2
1160
middle_value = arr[right_middle] + arr[right_middle - 1]
1161
return arr[:right_middle - 1] + [middle_value] + arr[right_middle + 1:]
1162
1163
def makeArrayConsecutive2(statues):
1164
count = 0
1165
for i in range(min(statues), max(statues)):
1166
if i not in statues:
1167
count += 1
1168
return count
1169
1170
def isPower(n):
1171
if n == 1:
1172
return True
1173
1174
a = 2
1175
b = 2
1176
while a ** 2 <= n:
1177
while a ** b <= n:
1178
if a ** b == n:
1179
return True
1180
b += 1
1181
b = 2
1182
a += 1
1183
return False
1184
def isSumOfConsecutive2(n):
1185
count = 0
1186
right = 2
1187
arr = [1, 2]
1188
while right <= (n // 2) + 1:
1189
total = sum(arr)
1190
if total == n:
1191
count += 1
1192
del arr[0]
1193
elif total < n:
1194
right += 1
1195
arr.append(right)
1196
elif total > n:
1197
del arr[0]
1198
return count
1199
1200
def squareDigitsSequence(a0):
1201
sequence = [a0]
1202
while sequence[-1] not in sequence[:-1]:
1203
next_value = 0
1204
for digit in str(sequence[-1]):
1205
next_value += int(digit) ** 2
1206
sequence.append(next_value)
1207
return len(sequence)
1208
1209
def pagesNumberingWithInk(current, numberOfDigits):
1210
numberOfDigits -= len(str(current))
1211
next_digits = len(str(current + 1))
1212
while numberOfDigits >= next_digits:
1213
current += 1
1214
numberOfDigits -= next_digits
1215
next_digits = len(str(current))
1216
return current
1217
1218
def comfortableNumbers(l, r):
1219
count = 0
1220
for a in range(l, r):
1221
for b in range(a + 1, r + 1):
1222
a_sum = sum(int(digit) for digit in str(a))
1223
b_sum = sum(int(digit) for digit in str(b))
1224
if b <= a + a_sum and a >= b - b_sum:
1225
count += 1
1226
return count
1227
1228
def weakNumbers(n):
1229
all_factors = [count_factors(num) for num in range(1, n+1)]
1230
weaknesses = []
1231
for num, num_factors in enumerate(all_factors, 1):
1232
weakness = 0
1233
for factor in all_factors[:num]:
1234
if factor > num_factors:
1235
weakness += 1
1236
weaknesses.append(weakness)
1237
weakest = max(weaknesses)
1238
return [weakest, weaknesses.count(weakest)]
1239
1240
def count_factors(n):
1241
factors = 0
1242
for i in range(1, n+1):
1243
if n % i == 0:
1244
factors += 1
1245
return factors
1246
1247
print(weakNumbers(500))
1248
import math
1249
1250
def rectangleRotation(a, b):
1251
n = a / (2 ** 0.5)
1252
m = b / (2 ** 0.5)
1253
points = (math.floor(n) * math.floor(m)) + (math.ceil(n) * math.ceil(m))
1254
if math.floor(n) % 2 != math.floor(m) % 2:
1255
points -= 1
1256
return points
1257
1258
# rectangleRotation(6, 4)
1259
print(rectangleRotation(8,6))
1260
1261
# def insertDashes(s):
1262
# return "-".join(s).replace("- -", " ")
1263
# 55
1264
1265
# insertDashes = lambda s: "-".join(s).replace("- -", " ")
1266
# 51
1267
1268
# return "-".join(*eval(dir()[0])).replace("- -", " ")
1269
# 50
1270
1271
# return re.sub("- -", " ", "-".join(*eval(dir()[0])))
1272
# 49
1273
1274
# insertDashes = lambda s: re.sub('\B', '-', s)
1275
# 39
1276
1277
return re.sub("\B", "-", *eval(dir()[0]))
1278
# 38
1279
1280
def digitDegree(n):
1281
degree = 0
1282
while 10 <= n:
1283
num = str(n)
1284
n = sum(int(i) for i in num)
1285
degree += 1
1286
return degree
1287
1288
def deleteDigit(n):
1289
num = str(n)
1290
result = list(int("".join(num[:i] + num[1 + i :])) for i in range(len(num)))
1291
return max(result)
1292
1293
def evenDigitsOnly(n):
1294
digits_of_n = []
1295
while n > 0:
1296
rem = n % 10
1297
digits_of_n.append(rem)
1298
n = int(n / 10)
1299
for i in range(len(digits_of_n)):
1300
if digits_of_n[i] % 2 != 0:
1301
return False
1302
return True
1303
1304
def longestDigitsPrefix(inputString):
1305
count = 0
1306
for i in range(len(inputString)):
1307
if inputString[i].isdigit():
1308
count += 1
1309
else:
1310
return inputString[0:count]
1311
return inputString
1312
1313
# def removeDuplicateStrings(a):
1314
# return list(OrderedDict.fromkeys(a))
1315
# 64
1316
1317
# removeDuplicateStrings = lambda a: list(OrderedDict.fromkeys(a))
1318
# 60
1319
1320
return list(OrderedDict.fromkeys(*eval(dir()[0])))
1321
# 49
1322
1323
def extractEachKth(inputArray, k):
1324
inp = []
1325
for i in range(len(inputArray)):
1326
if (i + 1) % k == 0:
1327
pass
1328
else:
1329
inp.append(inputArray[i])
1330
return inp
1331
1332
"""Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
1333
1334
Example:
1335
For inputArray = [3, 6, -2, -5, 7, 3], the output should be adjacentElementsProduct(inputArray) = 21.
1336
7 and 3 produce the largest product."""
1337
1338
1339
def adjacentElementsProduct(inputArray):
1340
# Step 1: Initially, define an empty array where we will store the products of adjacent elements from the input array.
1341
ArrayEnd = []
1342
# Step 2: Using a for-loop, we go over all entries of the input array, calculating the products of adjacent elements
1343
# and appending them to the empty array from step 1.
1344
for i in range(len(inputArray) - 1):
1345
ArrayEnd.append(inputArray[i] * inputArray[i + 1])
1346
# Step 3: We seek the largest entry in "ArrayEnd" from step 1, using the max() function.
1347
maximum = max(ArrayEnd)
1348
return maximum
1349
1350
"""After becoming famous, the CodeBots decided to move into a new building together.
1351
Each of the rooms has a different cost, and some of them are free, but there's a rumour that all the free rooms are haunted!
1352
Since the CodeBots are quite superstitious, they refuse to stay in any of the free rooms, or any of the rooms below any of the free rooms.
1353
1354
Given matrix, a rectangular matrix of integers, where each value represents the cost of the room, your task is to return
1355
the total sum of all rooms that are suitable for the CodeBots (ie: add up all the values that don't appear below a 0).
1356
1357
Example:
1358
For
1359
matrix = [[0, 1, 1, 2],
1360
[0, 5, 0, 0],
1361
[2, 0, 3, 3]]
1362
the output should be matrixElementsSum(matrix) = 9.
1363
1364
example 1: There are several haunted rooms, so we'll disregard them as well as any rooms beneath them.
1365
Thus, the answer is 1 + 5 + 1 + 2 = 9. (PICTURE PROVIDED AT:WWW.CODESIGNAL.COM)
1366
1367
For
1368
matrix = [[1, 1, 1, 0],
1369
[0, 5, 0, 1],
1370
[2, 1, 3, 10]]
1371
the output should be matrixElementsSum(matrix) = 9.
1372
1373
example 2:
1374
Note that the free room in the final column makes the full column unsuitable for bots (not just the room directly beneath it).
1375
Thus, the answer is 1 + 1 + 1 + 5 + 1 = 9. (PICTURE PROVIDED AT:WWW.CODESIGNAL.COM)"""
1376
1377
1378
def matrixElementsSum(matrix):
1379
# Step 1: We begin by defining the number of rows and columns inside our given matrix.
1380
# You can conceive the number of rows as the number of nested arrays inside the main array and
1381
# the number of columns as the number of elements in the first nested array.
1382
# Feel free to convince yourself that this is the case by referring to the examples of matrices shown above.
1383
rows = len(matrix)
1384
cols = len(matrix[0])
1385
# Step 2: Furthermore, create a new variable called "summ" (from summation) and set it equal to zero.
1386
# It will be used in the following for-loop.
1387
summ = 0
1388
# Step 3: Here we have an unusual for-inside-a-for loop (compared to the one that we usually observe when dealing with matrices).
1389
# As we are interested in the position of elements in columns (elements BELOW 0s), the outside for-loop works across all columns
1390
# whilst the nested for-loop works across all rows.
1391
for j in range(cols):
1392
for i in range(rows):
1393
# Step 4: If, while counting, the loop meets an element whose value is zero, the counting stops.
1394
# Otherwise, it continues counting, each time adding the value of the i-th / j-th element to the "summ" variable, defined in step 2.
1395
if matrix[i][j] == 0:
1396
break
1397
summ += matrix[i][j]
1398
# Step 5: Therefore, we end up with the total sum of non-zero elements whose position in a column is not
1399
# below an element of value zero.
1400
return summ
1401
1402
def findEmailDomain(address):
1403
address_spl = address.split("@")
1404
c = [i for i in address_spl]
1405
if len(address_spl) == 2:
1406
return c[1]
1407
if len(address_spl) == 3:
1408
return c[2]
1409
1410
from itertools import groupby
1411
1412
1413
def lineEncoding(s):
1414
s2 = ""
1415
for k, g in groupby(s):
1416
l = len(list(g))
1417
if l == 1:
1418
s2 += k
1419
else:
1420
s2 += str(l) + k
1421
return s2
1422
1423
def areEquallyStrong(yourLeft, yourRight, friendsLeft, friendsRight):
1424
personal_max = max(yourLeft, yourRight)
1425
friend_max = max(friendsLeft, friendsRight)
1426
sum1 = yourLeft + yourRight
1427
sum2 = friendsLeft + friendsRight
1428
if sum1 == sum2 and personal_max == friend_max:
1429
return True
1430
return False
1431
1432
import requests
1433
import pandas as pd
1434
1435
1436
def productExceptSelf(nums, m, first=True):
1437
# uses divide and conquer approach from Khan academy!
1438
# may need to upgrade with prime factorization
1439
# and fast modular exponents using binary!
1440
1441
# make map of prime factors and their exponents (number of each factor)
1442
# by breaking down individual array items
1443
# remove individual values from map for each item in array (reduce number of each factor present in current item)
1444
# convert exponent to binary and get modular exponents for each factor (see here: https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/fast-modular-exponentiation)
1445
# finally, combine all different prime factors for the number and add to array
1446
# reduce array by summing and final mod as shown
1447
if len(nums) == 1:
1448
return nums[0] % m
1449
if first:
1450
output = []
1451
j = len(nums)
1452
mid = (j - 1) // 2
1453
# left_mod = productExceptSelf(nums[0:mid], m, False)
1454
# right_mod = productExceptSelf(nums[mid:], m, False)
1455
for i in range(j):
1456
arr = nums[:]
1457
arr.pop(i)
1458
# print(arr)
1459
# if(i<mid):
1460
# mult_val = right_mod
1461
# else:
1462
# mult_val = left_mod
1463
output.append(productExceptSelf(arr, m, False))
1464
1465
# print(output)
1466
return sum(output) % m
1467
1468
else:
1469
mid = len(nums) // 2
1470
left = productExceptSelf(nums[0:mid], m, False)
1471
right = productExceptSelf(nums[mid:], m, False)
1472
return (left * right) % m
1473
1474
1475
arr = pd.read_json("./test-16.json").loc["nums", "input"]
1476
1477
# print(arr)
1478
1479
print(productExceptSelf(arr, 9999, first=True))
1480
1481
1482
# works for small cases, need to use divide and conquer according to Khan
1483
# causes overflow issues
1484
# #first, get the number of all nums multiplied
1485
# largest_num = 1
1486
# for num in nums:
1487
# largest_num*=num
1488
1489
# print(largest_num)
1490
1491
# #get the array of modulo m elements
1492
# fg_arr = [(largest_num/num) % m for num in nums]
1493
1494
# print(fg_arr)
1495
# total = sum(fg_arr) % m
1496
1497
# return total
1498
1499
# 52
1500
# def triangleExistence(t):
1501
# t.sort()
1502
# return t[0] + t[1] > t[2]
1503
1504
# 46
1505
# triangleExistence = lambda t: sum(t) - max(t) > max(t)
1506
1507
# 45
1508
# t, = eval(dir()[0])
1509
#
1510
# t.sort()
1511
# return t[0] + t[1] > t[2]
1512
1513
# 43
1514
# t, = eval(dir()[0])
1515
# return sum(t) - max(t) > max(t)
1516
1517
# 40
1518
a, b, c = sorted(*eval(dir()[0]))
1519
return a + b > c
1520
1521
def messageFromBinaryCode(code):
1522
phrase = ""
1523
bits = [int(code[i * 8 : i * 8 + 8], 2) for i in range(len(code) // 8)]
1524
for j in range(len(bits)):
1525
phrase += chr(bits[j])
1526
return phrase
1527
1528
1529
1530
1531
Copied!
1
2
3
"""Given a year, return the century it is in. The first century spans from the year 1 up to and including the year 100, the second -
4
from the year 101 up to and including the year 200, etc.
5
6
Example:
7
- For year = 1905, the output should be centuryFromYear(year) = 20;
8
- For year = 1700, the output should be centuryFromYear(year) = 17. """
9
10
11
def centuryFromYear(year):
12
# We begin by getting the INTEGER quotient of the division of the year given by 100.
13
# This will give us the first two digits, which would be the century.
14
cen = int(year / 100)
15
# However, we should keep in mind that we refer to years between e.g. 1701 - 1800
16
# as the "18th century". Hence, we implement a while loop, where the condition is
17
# that the year is a positive integer (which is always true). If the remainder of the
18
# division of the year by 100 is 0, then the two first digits of the division represent
19
# the century. Otherwise, if the remainder is non-zero, the century is found by adding 1
20
# to the result of the division (i.e. "cen").
21
while year >= 1:
22
if year % 100 == 0:
23
return year / 100
24
else:
25
return cen + 1
26
27
def isIPv4Address(inputString):
28
str_split = inputString.split(".")
29
count = 0
30
if len(str_split) != 4:
31
return False
32
for i in range(0, 4):
33
if str_split[i] == "" or str_split[i] == "00" or str_split[i] == "01":
34
return False
35
if re.search("[a-zA-Z]", str_split[i]):
36
count += 1
37
if count > 0:
38
return False
39
if str_split[i].isnumeric():
40
if int(str_split[i]) < 0:
41
return False
42
if int(str_split[i]) > 255:
43
return False
44
return True
45
46
"""Write a function that reverses characters in (possibly nested) parentheses in the input string.
47
Input strings will always be well-formed with matching ()s.
48
49
Example:
50
- For inputString = "(bar)", the output should be reverseInParentheses(inputString) = "rab";
51
- For inputString = "foo(bar)baz", the output should be reverseInParentheses(inputString) = "foorabbaz";
52
- For inputString = "foo(bar)baz(blim)", the output should be reverseInParentheses(inputString) = "foorabbazmilb";
53
- For inputString = "foo(bar(baz))blim", the output should be reverseInParentheses(inputString) = "foobazrabblim".
54
Because "foo(bar(baz))blim" becomes "foo(barzab)blim" and then "foobazrabblim"."""
55
56
57
def reverseInParentheses(inputString):
58
# Step 1: We create a for-loop that goes over all elements of the input string. If element i is an opening bracket, then i
59
# is defined as "start". In a similar manner, if element i is a closing bracket, i is defined as "end". NOTE THAT
60
# if you write it as "i = start" or "i = end", an error will pop up (tested) as you would have not defined any variables
61
# under those names, whilst the way that is written now you define as "start" and "end" elements that are
62
# "(" and ")" respectively.
63
for i in range(len(inputString)):
64
if inputString[i] == "(":
65
start = i
66
if inputString[i] == ")":
67
end = i
68
# Step 2: Furthermore, we apply the function inside itself and concatenate the individual modified parts:
69
# the part of the input string up to (and NOT including) the "starting" point (i.e. opening bracket) is left intact.
70
# The same goes for the part of the input string one element AFTER the "ending" point (i.e. closing bracket)
71
# till the actual end of the input string. The part of the input string that is located one element after
72
# the starting point ("start"+1 included) and up to the "ending" point NOT included is reversed.
73
return reverseInParentheses(
74
inputString[:start]
75
+ inputString[start + 1 : end][::-1]
76
+ inputString[end + 1 :]
77
)
78
# Step 3: To conclude, we return the modified input string.
79
return inputString
80
81
"""Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence
82
by removing no more than one element from the array.
83
84
Note: sequence a0, a1, ..., an is considered to be a strictly increasing if a0 < a1 < ... < an.
85
Sequence containing only one element is also considered to be strictly increasing.
86
87
Example:
88
- For sequence = [1, 3, 2, 1], the output should be almostIncreasingSequence(sequence) = false.
89
There is no one element in this array that can be removed in order to get a strictly increasing sequence.
90
- For sequence = [1, 3, 2], the output should be almostIncreasingSequence(sequence) = true.
91
You can remove 3 from the array to get the strictly increasing sequence [1, 2].
92
Alternately, you can remove 2 to get the strictly increasing sequence [1, 3]."""
93
94
95
def almostIncreasingSequence(sequence):
96
# Step 1: We begin by assigning the length of the given sequence to the variable n.
97
n = len(sequence)
98
# Step 2: By definition, if the sequence contains up to 1 elements, it is considered to be strictly increasing.
99
if n <= 2:
100
return True
101
# Step 3: We set up two counters, namely c1 and c2, so that we count how many elements should be removed.
102
# NOTE THAT c1 refers ONLY to adjacent elements whilst c2 refers to elements just before and just after the i-th element.
103
c1 = 0
104
c2 = 0
105
# Step 4: This for-loop (and its content) is a tricky part. The range of the for-loop starts from 1 and goes all the way to (n-1)th element.
106
# BE CAREFUL: We set n-1 to avoid getting our index out of range in the second if statement inside the for-loop.
107
for i in range(1, n - 1):
108
# Step 5: If the element prior to the index element i has a bigger value than i, we add 1 hit to the first counter.
109
if sequence[i - 1] >= sequence[i]:
110
c1 += 1
111
# Step 6: If the element just before the index element i has a bigger value than the element just after i,
112
# we add 1 hit to the second counter.
113
if sequence[i - 1] >= sequence[i + 1]:
114
c2 += 1
115
# Step 7: If the element two places to the left of the index element i has a bigger value than the element prior to i,
116
# we add 1 hit to the first counter.
117
if sequence[n - 1] <= sequence[n - 2]:
118
c1 += 1
119
# Step 8: If BOTH of the counters have up to 1 hit (that means 0 or 1 EACH), then the sequence is almost increasing.
120
if c1 <= 1 and c2 <= 1:
121
return True
122
else:
123
return False
124
125
import itertools as t
126
127
128
def chessKnight(cell):
129
knight_dir = list(t.permutations([1, 2, -1, -2], 2))
130
knight_dir1 = []
131
valid_moves = 0
132
for i in range(len(knight_dir)):
133
if sum(knight_dir[i]) != 0:
134
knight_dir1.append(knight_dir[i])
135
for x, y in knight_dir1:
136
if (97 <= ord(cell[0]) + x <= 104) and (1 <= int(cell[1]) + y <= 8):
137
valid_moves += 1
138
return valid_moves
139
140
def knapsackLight(value1, weight1, value2, weight2, maxW):
141
if weight1 > maxW and weight2 > maxW and weight1 + weight2 > maxW:
142
return 0
143
if weight1 + weight2 <= maxW:
144
return value1 + value2
145
if value1 < value2:
146
if weight2 > maxW:
147
return value1
148
else:
149
return value2
150
if value2 < value1:
151
if weight1 > maxW:
152
return value2
153
else:
154
return value1
155
if value1 == value2:
156
if weight1 > maxW:
157
return value2
158
else:
159
return value1
160
161
"""
162
Given a non-empty, singly linked list with head node head, return a middle node of linked list.
163
164
If there are two middle nodes, return the second middle node.
165
166
"""
167
168
169
# Definition for singly-linked list.
170
class ListNode:
171
def __init__(self, x):
172
self.val = x
173
self.next = None
174
175
176
class Solution:
177
def middleNode(self, head: ListNode) -> ListNode:
178
get_len = 0
179
current = head
180
while current:
181
get_len += 1
182
current = current.next
183
mid = get_len // 2
184
current = head
185
while mid > 0:
186
current = current.next
187
mid -= 1
188
return current
189
190
"""Given an array of strings, return another array containing all of its longest strings.
191
192
Example:
193
For inputArray = ["aba", "aa", "ad", "vcd", "aba"], the output should be allLongestStrings(inputArray) = ["aba", "vcd", "aba"]."""
194
195
196
def allLongestStrings(inputArray):
197
# Step 1: We begin by defining an empty array called "max_arr", where we will store the longest strings from the given array.
198
max_arr = []
199
# Step 2: The next step is to define the maximum string length inside our given array.
200
# BE CAREFUL: Variable max_len should be defined as follows. If we break it into its components, we can see that:
201
# max(inputArray, key = len) locates ONLY ONE of the strings that satisfies the maximum value in terms of the key parameter
202
# provided (which, in this case, is the string's length) and the outside len() function defines the value of this maximum length.
203
# You are free to test it on a random input array containing various random strings, using a Python compiler online.
204
max_len = len(max(inputArray, key=len))
205
# Step 3: Now, we go over all strings inside the input array checking if their individual length is equal to the
206
# maximum length value defined in step 2. If it is, then we append the respective string to the "max_arr" defined above.
207
for i in inputArray:
208
if len(i) == max_len:
209
max_arr.append(i)
210
# Step 4: We conclude by returning the max_arr.
211
return max_arr
212
213
"""Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky
214
if the sum of the first half of the digits is equal to the sum of the second half.
215
Given a ticket number n, determine if it's lucky or not.
216
217
Example
218
- For n = 1230, the output should be isLucky(n) = true;
219
- For n = 239017, the output should be isLucky(n) = false."""
220
221
222
def isLucky(n):
223
# Step 1: We begin by creating an empty array, called "digits_of_n",
224
# where we will store the digits of the given number n, as individual elements.
225
digits_of_n = []
226
# Step 2: We also create a new variable, called "summ" (from summation), and set its value to zero.
227
# It will be useful in one of the later steps.
228
summ = 0
229
# Step 3: I have personally seen this while-loop trick being used to split numbers into their individual digits.
230
# As it will take quite a long text to explain this comprehensively, I'd suggest you use the print() function in each
231
# step to see what how each of these steps works. The important thing to mention is the "appending" step where each
232
# digit, where each digit is stored as an elememnt in "digits_of_n" array.
233
while n > 0:
234
rem = n % 10
235
digits_of_n.append(rem)
236
n = int(n / 10)
237
# Step 4: Furthermore, we implement a for-loop that goes over all elements inside the "digits_of_n" array, one by one.
238
# If the element's index is up to the middle of the length of the array, we add the element's numeric value to "summ".
239
# Otherwise, we subtract it. NOTE THAT for arrays of even length, you can find the "middle" by dividing the length by 2
240
# (i.e. for arrays of length 4, the 2nd element is the "middle), whilst for array of odd length, the "middle" is the
241
# element having equal numbers of elements on both its sides.
242
for i in range(len(digits_of_n)):
243
if i < len(digits_of_n) / 2:
244
summ += digits_of_n[i]
245
else:
246
summ -= digits_of_n[i]
247
# Step 5: Finally, we check if the summation is zero or not. If the sum is zero, then the ticket number is lucky,
248
# according to the definition of the exercise.
249
if summ == 0:
250
return True
251
return False
252
253
def isMAC48Address(inputString):
254
str_split = inputString.split("-")
255
count = 0
256
if len(inputString) != 17:
257
return False
258
if len(str_split) != 6:
259
return False
260
for i in range(0, 6):
261
if str_split[i] == "":
262
return False
263
if re.search("[a-zG-Z]", str_split[i]):
264
count += 1
265
if count > 0:
266
return False
267
return True
268
269
def arrayMaxConsecutiveSum(inputArray, k):
270
arr = [sum(inputArray[:k])]
271
for i in range(1, len(inputArray) - (k - 1)):
272
arr.append(arr[i - 1] - inputArray[i - 1] + inputArray[i + k - 1])
273
sort_arr = sorted(arr)
274
return sort_arr[-1]
275
276
def arrayMaximalAdjacentDifference(inputArray):
277
return max(
278
(abs(inputArray[i + 1] - inputArray[i]) for i in range(0, len(inputArray) - 1))
279
)
280
281
p, s = eval(dir()[0])
282
r = -1
283
l = len(p)
284
for i in range(l):
285
for j in range(l):
286
c = 0
287
d = p[j] - p[i]
288
f = s[i] - s[j]
289
290
if d * f < 1:
291
continue
292
293
for k in range(l):
294
if p[k] * f + s[k] * d == p[i] * f + s[i] * d:
295
c += 1
296
if c > r:
297
r = c
298
return r
299
300
# def smallestMultiple(l, r):
301
# for i in range(1,8**7):
302
# s = True
303
# for j in range(l, r+1):
304
# if i%j!=0:
305
# s = False
306
# if s:
307
# return i
308
309
310
def smallestMultiple(l, r):
311
for i in range(1, 16):
312
for j in range(l, r + 1):
313
while True:
314
if i % j != 0:
315
break
316
return i
317
318
def variableName(name):
319
str_name = [i for i in str(name)]
320
non_acc_chars = [
321
" ",
322
">",
323
"<",
324
":",
325
"-",
326
"|",
327
".",
328
",",
329
"!",
330
"[",
331
"]",
332
"'",
333
"/",
334
"@",
335
"#",
336
"&",
337
"%",
338
"?",
339
"*",
340
]
341
if str_name[0] in str([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]):
342
return False
343
for j in range(len(str_name)):
344
if str_name[j] in non_acc_chars:
345
return False
346
return True
347
348
def fileNaming(names):
349
if names == []:
350
return []
351
new_names = []
352
for name in names:
353
if name not in new_names:
354
new_names.append(name)
355
else:
356
for i in range(1, 1000):
357
new_name = name + "(" + str(i) + ")"
358
if new_name not in new_names:
359
new_names.append(new_name)
360
break
361
return new_names
362
363
from collections import Counter
364
365
366
def singleNumber(nums):
367
"""
368
given a list of integer with every element appears twice and a single number appears once, return the value of the
369
single number
370
"""
371
count = Counter(nums)
372
for k, v in count.items():
373
if v == 1:
374
return k
375
376
377
print(singleNumber([2, 2, 4, 1, 5]))
378
379
memo = {}
380
381
382
def isHappy(n):
383
"""
384
Is happy takes in a number and returns True if it is a happy number, False otherwise. A happy number
385
is a number defined by the following process: Starting with any positive integer, replace the number by the
386
sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay),
387
or it loops endlessly in a cycle which does not include 1.
388
"""
389
seen = {n: 1}
390
while True:
391
new_sq = sum([int(d) ** 2 for d in str(n)])
392
if n == 1:
393
return True
394
if new_sq in seen:
395
return False
396
else:
397
n = new_sq
398
seen[n] = 1
399
400
401
print(isHappy(19))
402
403
def spiralNumbers(n):
404
dims = n
405
elem = 1
406
matrix = [[0] * n for x in range(n)]
407
while 0 < dims:
408
i = n - dims
409
# you can sub i = n - dims ONLY in the first 2 parts
410
# where n - dims is in the starting parameter of the range
411
for j in range(n - dims, dims):
412
matrix[i][j] = elem
413
elem += 1
414
for i in range(n - dims + 1, dims):
415
matrix[i][j] = elem
416
elem += 1
417
for j in range(dims - 2, n - dims - 1, -1):
418
matrix[i][j] = elem
419
elem += 1
420
for i in range(dims - 2, n - dims, -1):
421
matrix[i][j] = elem
422
elem += 1
423
dims -= 1
424
return matrix
425
426
def avoidObstacles(inputArray):
427
for i in range(2, max(inputArray) + 2):
428
if i not in inputArray and all(j % i != 0 for j in inputArray):
429
return i
430
431
def circleOfNumbers(n, firstNumber):
432
return ((n / 2) + firstNumber) % n
433
434
def sumOfSquares(n):
435
return sum([x ** 2 for x in range(1, n + 1)])
436
437
# def sumOfTheAngles(n):
438
# return (n - 2) * 180
439
440
sumOfTheAngles = lambda n: (n - 2) * 180
441
442
# n = eval(dir()[0])
443
# return (n - 2) * 180
444
445
def sumOfTwo(a, b, v):
446
b = set(b)
447
return any(v - i in b for i in a)
448
449
def visitsOnCircularRoad(n, v):
450
c = 1
451
t = 0
452
for i in v:
453
t += min(abs(i - c), abs(n - abs(i - c)))
454
c = i
455
return t
456
457
458
# v = visitsOrder
459
# n = number of houses
460
# c = Current position
461
# t = Time
462
463
def buildPalindrome(st):
464
for i in range(len(st)):
465
sub = st[i : len(st)]
466
if sub[::-1] == sub:
467
missing = st[0:i]
468
return st + missing[::-1]
469
return st
470
471
checkPalindrome = lambda x: x == x[::-1]
472
473
# greetPerson = lambda n: "Hello, " + n
474
475
greetPerson = "Hello, {}".format
476
477
def growingPlant(upSpeed, downSpeed, desiredHeight):
478
day_count = 0
479
height = 0
480
while height <= desiredHeight:
481
height = height + upSpeed
482
day_count += 1
483
if height < desiredHeight:
484
height = height - downSpeed
485
else:
486
return day_count
487
488
def twoPointerSum(nums, target):
489
"""
490
Given a sorted array of integers, return indices of the two numbers such that they add up to a specific target.
491
You may assume that each input would have exactly one solution, and you may not use the same element twice.
492
"""
493
l = 0
494
r = len(nums) - 1
495
while l < r:
496
if nums[l] + nums[r] == target:
497
return [l, r]
498
elif nums[l] + nums[r] > target:
499
r -= 1
500
else:
501
l += 1
502
503
504
nums = [5, 25, 75]
505
target = 100
506
print(twoPointerSum(nums, target))
507
508
# def gasPrediction(driveDistances, currentGasLevel, avgMileage):
509
# a = sum(driveDistances) / 12 / avgMileage
510
# print(a)
511
# if a > currentGasLevel:
512
# return True
513
# else:
514
# return False
515
516
# d, c, a = eval(dir()[0])
517
# return sum(d) / 12 / a > c
518
519
# 39 chars
520
gasPrediction = lambda d, c, a: sum(d) / 12 / a > c
521
522
def digitsProduct(product):
523
if product == 0:
524
return 10
525
if product == 1:
526
return 1
527
for i in range(0, 4000):
528
p = 1
529
for j in str(i):
530
p *= int(j)
531
if p == product:
532
return i
533
return -1
534
535
def depositProfit(deposit, rate, threshold):
536
i = 0
537
while deposit < threshold:
538
deposit += deposit * rate * 0.01
539
i += 1
540
return i
541
542
def depositProfit(deposit, rate, threshold):
543
year_count = 0
544
while deposit < threshold:
545
deposit = deposit + (deposit * (rate / 100))
546
year_count += 1
547
return year_count
548
549
from itertools import permutations as p
550
551
552
def stringsRearrangement(inputArray):
553
p_list = list(p(inputArray))
554
for i in range(len(p_list)):
555
count1 = 0
556
for j in range(len(p_list[0]) - 1):
557
count2 = 0
558
for k in range(len(p_list[0][0])):
559
if p_list[i][j][k] != p_list[i][j + 1][k]:
560
count2 += 1
561
if count2 == 1:
562
count1 += 1
563
if count1 >= (len(p_list[0])) - 1:
564
return True
565
return False
566
567
def palindromeRearranging(inputString):
568
odd_count = 0
569
char_set = set(inputString)
570
for i in char_set:
571
char_count = inputString.count(i)
572
if char_count % 2 != 0:
573
odd_count += 1
574
if odd_count <= 1:
575
return True
576
return False
577
578
# def fractionReducing(f):
579
# return [i / math.gcd(f[0], f[1]) for i in f]
580
581
# fractionReducing = lambda f: [i / math.gcd(f[0], f[1]) for i in f]
582
583
f, = eval(dir()[0])
584
return [i / math.gcd(f[0], f[1]) for i in f]
585
586
def arrayReplace(inputArray, elemToReplace, substitutionElem):
587
new = []
588
for i in range(len(inputArray)):
589
if inputArray[i] == elemToReplace:
590
new.append(substitutionElem)
591
else:
592
new.append(inputArray[i])
593
return new
594
595
def alphabeticShift(inputString):
596
return "".join(chr(ord(i) + 1) if i != "z" else "a" for i in inputString)
597
598
def areSimilar(a, b):
599
check_a = []
600
check_b = []
601
count = 0
602
for i in range(len(a)):
603
if a[i] != b[i]:
604
count += 1
605
check_a.append(a[i])
606
check_b.append(b[i])
607
if count == 0:
608
return True
609
elif count == 2:
610
return set(check_a) == set(check_b)
611
else:
612
return False
613
614
def differentSquares(matrix):
615
rows = len(matrix)
616
cols = len(matrix[0])
617
sq_arr = []
618
sq_count = 0
619
for i in range(rows - 1):
620
for j in range(cols - 1):
621
sq_2x2 = [
622
matrix[i][j],
623
matrix[i][j + 1],
624
matrix[i + 1][j],
625
matrix[i + 1][j + 1],
626
]
627
if sq_2x2 not in sq_arr:
628
sq_arr.append(sq_2x2)
629
sq_count += 1
630
return sq_count
631
632
def maxSubarray(A):
633
# A: inputArray
634
# m: Max
635
#
636
#
637
m = e = 0
638
for i in A:
639
e += i
640
if e < 0:
641
e = 0
642
if m < e:
643
m = e
644
return m
645
646
l, s = eval(dir()[0])
647
r = []
648
c = 1
649
650
t = [[int(s[i : i + 2]) for i in [1, 4]] + [s[7:9]] for s in l]
651
t = [f"{x // 60:02d}:{x % 60:02d}:{y:02d},{z.ljust(3, str(0))}" for x, y, z in t] + [
652
s + ",000"
653
] # if I replace str(0) with '0', this increases to 359 characters wtf
654
655
for a, b in enumerate(l):
656
r.extend([str(c), t[a] + " --> " + t[a + 1], b[11:], ""])
657
c += 1
658
return r[:-1]
659
660
# def mySubstring(s, l, r):
661
# return s[l:r+1]
662
663
mySubstring = lambda s, l, r: s[l : r + 1]
664
665
def isSum(value):
666
s = 0
667
for i in range(100):
668
s += i
669
if s == value:
670
return True
671
672
# def countSumOfTwoRepresentations3(n, l, r):
673
# if r < n // 2 or l > n // 2:
674
# return 0
675
# return n // 2 - max(l, n-r) + 1
676
# 87
677
678
# countSumOfTwoRepresentations3 = lambda n, l, r: max(n // 2 - max(l, n-r) + 1, 0)
679
# 66
680
681
n, l, r = eval(dir()[0])
682
return max(n // 2 - max(l, n - r) + 1, 0)
683
# 50
Copied!
Last modified 2mo ago
Export as PDF
Copy link